Junior — Middle
Is it possible to merge or add two classes in Python by creating a new object that combines their properties?
sobes.tech AI
Answer from AI
Yes, in Python, you can create a new object that combines the properties of two classes using multiple inheritance or dynamic creation of a new class.
Example with multiple inheritance:
class A:
def __init__(self):
self.a = 1
class B:
def __init__(self):
self.b = 2
class C(A, B):
def __init__(self):
A.__init__(self)
B.__init__(self)
obj = C()
print(obj.a) # 1
print(obj.b) # 2
You can also use the type function to dynamically create a class that combines properties:
C = type('C', (A, B), {})
obj = C()
Thus, the new object will contain properties of both classes.