我正试图让某种静态继承发生.下面的代码打印"nope".我不确定如何解释自己,但我想要的是A类使用B的方法(如果存在的话).
class A(object):
@staticmethod
def test():
print("nope")
@staticmethod
def test2():
__class__.test()
class B(A):
@staticmethod
def test():
print("It Works")
@staticmethod
def run():
__class__.test2()
if __name__ == "__main__":
B.run()
Run Code Online (Sandbox Code Playgroud)
__class__作为闭包引用从未打算用作对当前实例类型的引用; 它总是引用你定义方法的类(例如Afor A.test2).它是super()函数使用的内部实现细节.不要在这里使用它.
使用@classmethod代替;
class A(object):
@classmethod
def test(cls):
print("nope")
@classmethod
def test2(cls):
cls.test()
class B(A):
@classmethod
def test(cls):
print("It Works")
@classmethod
def run(cls):
cls.test2()
if __name__ == "__main__":
B.run()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
99 次 |
| 最近记录: |