我具有以下两个类A和B。如何使do_someting()方法在B中调用重写方法some_method()。这在Python中可行吗?
class A:
@staticmethod
def some_method()
# pass
return
@classmethod
def do_something():
A.some_method()
...
return
class B(A):
@staticmethod
def some_method()
# how does do_something call here?
return
@classmethod
def run()
B.do_something()
return
答案 0 :(得分:1)
这非常简单,只需确保在self
和cls
中修复冒号即可:
class A:
@staticmethod
def some_method():
# pass
return
@classmethod
def do_something(cls):
cls.some_method()
return
class B(A):
@staticmethod
def some_method():
print("I did stuff!")
return
@classmethod
def run(cls):
B.do_something()
return
k = B()
k.run()
>>>"I did stuff!"
如果您要从B类调用旧的do_something
(A类中的那个),只需传入相应的类即可。在B类中:
@classmethod
def run(cls):
A.do_something()
return