20

For example, I have a base class and a derived class:

>>> 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'

Is it possible to have the Derived class be able to call myClassMethod without overwriting it and calling super's class method? I'd like to overwrite the class method only when it's necessary.

4

2 回答 2

23

是的,它们可以被继承。

如果你想继承成员,你需要告诉python继承!

>>> class Derived(Base):
...    pass

在 Python 2 中,让你的Base类从对象继承是一个很好的做法(但它可以在你不这样做的情况下工作)。在 Python 3 中这是不必要的,因为它默认已经从 object 继承(除非你试图让你的代码向后兼容):

>>> class Base(object):
...     ...
于 2012-06-07T16:49:08.183 回答
5

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

class Derived(Base):
    ...
于 2012-06-07T16:49:05.967 回答