可以继承python @classmethod吗?

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)

  • 这只是python 2.x中的一个好习惯 - 在3.x中它是多余的,因为所有东西都继承自`object`. (12认同)
  • @James:是的,但关于SO的大多数问题仍然是2.7左右 (5认同)
  • @Daerdemandt然后我们编辑答案说"对于Python 2.x这是一个很好的做法......"并称之为一天 (3认同)

Ale*_*gov 7

您必须从子类中的基类派生:

class Derived(Base):
    ...
Run Code Online (Sandbox Code Playgroud)