Python类装饰器
我试图用以下代码装饰一个实际的类:Python类装饰器,python,decorator,Python,Decorator,我试图用以下代码装饰一个实际的类: def my_decorator(cls): def wrap(*args, **kw): return object.__new__(cls) return wrap @my_decorator class TestClass(object): def __init__(self): print "__init__ should run if object.__new__ correctly
def my_decorator(cls):
def wrap(*args, **kw):
return object.__new__(cls)
return wrap
@my_decorator
class TestClass(object):
def __init__(self):
print "__init__ should run if object.__new__ correctly returns an instance of cls"
test = TestClass() # shouldn't TestClass.__init__() be run here?
我没有收到任何错误,但我也看不到来自TestClass.\uuu init\uuuu()
的消息
根据:
典型的实现通过使用super(currentclass,cls)调用超类的\uuuuu new\uuuu()
方法来创建类的新实例。使用适当的参数来调用超类的\uu new\uuuu()
,然后在返回它之前根据需要修改新创建的实例
如果\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
知道为什么\uuuu init\uuuu
没有运行吗
此外,我还试着像这样调用\uuuuu new\uuuu
:
return super(cls.__bases__[0], cls).__new__(cls)
但它将返回一个类型错误:
TypeError: super.__new__(TestClass): TestClass is not a subtype of super
\uuuuu init\uuuu
未运行,因为对象。\uuuuu new\uuuu
不知道如何调用它。如果你把它改成
cls.\uuuuuu调用(*args,**kwargs)
,或者更好的调用cls(*args,**kwargs)
,它应该可以工作。请记住,类是可调用的:调用它会生成一个新实例。只需调用\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
即可返回一个实例,但不进行初始化。另一种方法是调用\uuuu new\uuuu
,然后手动调用\uuuu init\uuuu
,但这只是替换\uuu call\uuu
中已经包含的逻辑
您引用的文档是指从类的\uuuu new\uuu
方法中调用super
。在这里,你是从外部调用它,而不是以我已经讨论过的通常方式 无法告诉您原因,但此黑客确实运行了\uuuuu init\uuuuu
def my_decorator(cls):
print "In my_decorator()"
def wrap(*args, **kw):
print "In wrap()"
return cls.__init__(object.__new__(cls), *args, **kw)
return wrap
@my_decorator
class TestClass(object):
def __init__(self):
print "__init__ should run if object.__new__ correctly returns an instance of cls"
出于某种原因,我认为创建实例的行为会触发\uuuu init\uuuu
。谢谢你的澄清!