'How do you inherit the attributes of multiple classes in Python?
Problem:
i'm building a program that required being able to have the same attributes to multiple classes. those attributes have to be stored somewhere for classes to use for their instances.
let's say we have 2 classes:
class A():
def __init__(self, a):
self.a = a
class B():
def __init__(self, b):
self.b = b
i want to create a third class that contains the attributes a and b from both A and B respectively. how do you do so?
Attempts:
composition doesn't work because i'd have to redeclare the name like this which is error-prone once i end up mistyping a letter:
class C():
def __init__(self, a: A, b: B):
self.a = a
self.b = b
that's also a mess when you have to access values, like C().a.a is unclean, but i'm expecting more of C().a
inheritance with super() doesn't work either:
class A():
def __init__(self, a):
self.a = a
super().__init__() # no way to pass the variable "b"
class B():
def __init__(self, b):
self.b = b
super().__init__() # no way to pass the variable "a"
class C(A, B):
def __init__(self, a, b):
super().__init__(???) # no way to pass the variables to each specific class
Solution 1:[1]
You cannot pass value to instance A() or B(), but is class accepted.
class A:
a = 'aa'
class B:
b = 'bb'
class C:
def __init__(self, a: A = A(), b: B = B()):
self.a = a.a
self.b = b.b
print(C().a)
# aa
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Michael H |
