本文介绍了继承自装饰类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我正在尝试用另一个类来装饰一个类。我也想继承装饰类,但是我遇到了一些错误。这是我的代码: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@Decoratorclass Foo: passclass Goo(Foo): pass我尝试从 Foo 进行子类化时得到的错误是:The error I get when I try to subclass from Foo is this:通过向装饰器添加另一个初始化函数 ...def __init__(self, *args): for arg in args: print(arg) ...我得到以下输出:... I get the following output:这些参数是什么以及我应该如何在里面使用它们装饰者?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:@Decoratorclass Foo: pass相当于:class Foo: passFoo = 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) 这篇关于继承自装饰类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-20 09:22