yuk*_*lai 15 python inheritance class-method
例如,我有一个基类和一个派生类:
>>> class Base:
... @classmethod
... def myClassMethod(klass):
... pass
...
>>> class Derived:
... pass
...
>>> Base.myClassMethod()
>>> Derived.myClassMethod()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: class Derived has no attribute 'myClassMethod'
Run Code Online (Sandbox Code Playgroud)
是否有可能让Derived类能够调用myClassMethod而不覆盖它并调用super的类方法?我只想在必要时覆盖类方法.
Eri*_*ric 20
是的,他们可以继承.
如果你想继承成员,你需要告诉python继承!
>>> class Derived(Base):
... pass
Run Code Online (Sandbox Code Playgroud)
在Python 2中,让你的Base类从对象继承是一个很好的做法(但是没有你这样做它会工作).在Python 3中,它是不必要的,因为它默认已经从对象继承(除非你试图使你的代码向后兼容):
>>> class Base(object):
... ...
Run Code Online (Sandbox Code Playgroud)