Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a python @classmethod be inherited?

Tags:

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.

like image 880
yuklai Avatar asked Jun 07 '12 16:06

yuklai


People also ask

Are Classmethods inherited?

Yes, they can be inherited.

Can we inherit static class in Python?

Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor. However, they can contain a static constructor.

Do Python subclasses inherit methods?

Classes called child classes or subclasses inherit methods and variables from parent classes or base classes.

Are Python properties inherited?

Inheritance allows us to define a class that inherits all the methods and properties from another class. Parent class is the class being inherited from, also called base class. Child class is the class that inherits from another class, also called derived class.


2 Answers

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):
...     ...
like image 52
Eric Avatar answered Sep 23 '22 10:09

Eric


You must derive from the base class in subclass:

class Derived(Base):
    ...
like image 44
Aleksei astynax Pirogov Avatar answered Sep 26 '22 10:09

Aleksei astynax Pirogov