继承自装饰类 [英] Inheriting from decorated classes

查看:180
本文介绍了继承自装饰类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用另一个类来装饰一个类。我也想继承装饰类,但是我遇到了一些错误。这是我的代码:

I'm trying to decorate a class with another class. I also want to inherit from the decorated class, but I get some errors. Here's my code:

class Decorator:
    def __init__(self, decorated):
        pass

@Decorator
class Foo:
    pass

class Goo(Foo):
    pass

我尝试从 Foo 进行子类化时得到的错误是:

The error I get when I try to subclass from Foo is this:


回溯(最近一次呼叫最后一次):

   文件test.py,第9行,在< br>
       class Goo(Foo):

TypeError:__ init __()需要2个位置参数(给定4个)

Traceback (most recent call last):
   File "test.py", line 9, in
      class Goo(Foo):
TypeError: __init__() takes exactly 2 positional arguments (4 given)

通过向装饰器添加另一个初始化函数 ...

def __init__(self, *args):
    for arg in args:
        print(arg)

...我得到以下输出:

... I get the following output:


< class'__main __。Foo'>

Goo

(< __ main __。装饰器对象位于0x010073B0>,)< br>
{'__module__':'_ _ main __'}

<class '__main__.Foo'>
Goo
(<__main__.Decorator object at 0x010073B0>,)
{'__module__': '__main__'}

这些参数是什么以及我应该如何在里面使用它们装饰者

What are those parameters and how should I be using them inside Decorator?

推荐答案

我会尽力回答什么是那些参数问题。此代码:

I'll try to answer the "what are those parameters" question. This code:

@Decorator
class Foo:
    pass

相当于:

class Foo:
    pass
Foo = Decorator(Foo)

这意味着 Foo 最终成为装饰器类的实例而不是类。

This means that Foo ends up being an instance of the Decorator class instead of being a class.

当您尝试将此实例用作类的基础( Goo )时,Python必须确定一个元类,将用于创建新类。在这种情况下,它将使用 Foo .__ class __ 等于装饰器。然后它将使用(name,bases,dict)参数调用元类,并期望它返回一个新类。

When you try to use this instance as a base of a class (Goo), Python will have to determine a metaclass that will be used to create the new class. In this case it will use Foo.__class__ which equals to Decorator. Then it will call the metaclass with (name, bases, dict) arguments and expect it to return a new class.

这是你在装饰器.__ init __ 中结束这些参数的方法。

This is how you end up with these arguments in Decorator.__init__.

关于这一点的更多信息可以找到这里:
http://www.python.org/download/releases/2.2 .3 / descrintro / #metaclasses
(特别是当执行类声明时......部分)

More about this can be found here: http://www.python.org/download/releases/2.2.3/descrintro/#metaclasses (particularly the "When a class statement is executed..." part)

这篇关于继承自装饰类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆