我试图用这段代码装饰一个实际的类:
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?
Run Code Online (Sandbox Code Playgroud)
我没有错误,但我也没有看到消息TestClass.__init__()
.
根据新式课程的文档:
典型的实现通过
__new__()
使用super(currentclass, cls).__new__(cls[, ...])
适当的参数调用超类的方法然后在返回之前根据需要修改新创建的实例来创建类的新实例.如果
__new__()
返回cls的实例,则将__init__()
调用新实例的方法__init__(self[, ...])
,其中self是新实例,其余参数与传递给的相同__new__()
.
任何想法为什么__init__
不运行?
另外,我试着__new__
像这样打电话:
return super(cls.__bases__[0], cls).__new__(cls)
Run Code Online (Sandbox Code Playgroud)
但它会返回TypeError
:
TypeError: super.__new__(TestClass): TestClass is not a subtype of super
Run Code Online (Sandbox Code Playgroud)
aar*_*ing 10
__init__
没有运行,因为object.__new__
不知道调用它.如果您将其更改为
cls.__call__(*args, **kwargs)
或更好cls(*args, **kwargs)
,它应该可以工作.请记住,类是可调用的:调用它会生成一个新实例.只是调用__new__
返回一个实例但不进行初始化.另一种方法是调用__new__
然后手动调用,__init__
但这只是替换已经体现的逻辑__call__
.
你们报的文件指的是呼叫super
从内部的__new__
类的方法.在这里,你是从外面调用它,而不是像我已经讨论过的那样.
归档时间: |
|
查看次数: |
2644 次 |
最近记录: |