简体   繁体   中英

Can a python @classmethod be inherited?

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.

Yes, they can be inherited.

If you want to inherit members, you need to tell python about the inheritance!

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

In Python 2 it's a good practice to make your Base class inherit from object (but it will work without you doing so). In Python 3 it's unnecessary, since it already inherits from object by default (unless you're trying to make your code backwards compatible):

>>> class Base(object):
...     ...

You must derive from the base class in subclass:

class Derived(Base):
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM