Say I have a list of class objects in Python (A, B, C
) and I want to inherit from all of them when building class D
, such as:
class A(object):
pass
class B(object):
pass
class C(object):
pass
classes = [A, B, C]
class D(*classes):
pass
Unfortunately I get a syntax error when I do this. How else can I accomplish it, other than by writing class D(A, B, C)
? (There are more than three classes in my actual scenario)
It is not possible.
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.
Creating a class that inherits from another class To create a class that inherits from another class, after the class name you'll put parentheses and then list any classes that your class inherits from. In a function definition, parentheses after the function name represent arguments that the function accepts.
A class can be derived from more than one base class in Python, similar to C++. This is called multiple inheritance. In multiple inheritance, the features of all the base classes are inherited into the derived class. The syntax for multiple inheritance is similar to single inheritance.
You can dynamically create classes using type
keyword, as in:
>>> classes = [A, B, C]
>>> D = type('D', tuple(classes), {})
>>> type(D)
<class 'type'>
>>> D.__bases__
(<class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>)
see 15247075 for more examples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With