class Foo():
def __init__(self):
pass
def create_another(self):
return Foo()
# is not working as intended, because it will make y below becomes Foo
class Bar(Foo):
pass
x = Bar()
y = x.create_another()
Run Code Online (Sandbox Code Playgroud)
你应该是Bar not Foo.
是否有类似的东西self.constructor()?
Mar*_*ers 26
对于新式类,用于type(self)获取"当前"类:
def create_another(self):
return type(self)()
Run Code Online (Sandbox Code Playgroud)
您也可以使用self.__class__该值type(),但始终建议使用API方法.
对于旧式类(python 2,不是继承object),type()没有那么有用,所以你被迫使用self.__class__:
def create_another(self):
return self.__class__()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7009 次 |
| 最近记录: |