Reputation: 155
I'm working with multiple classes that share some initial common variables/attributes. In order to make it cleaner and avoid calling the same variables multiple times I want to set them all in an initial class (e.g. classA
) and then load all this attributes in a classB
.
So I would define:
class classA:
def __init__(self, varA, varB, varC, ..., varZ):
self.varA = varA
self.varB = varB
self.varC = varC
(...)
self.varZ = varZ
And then load it in a second classB
class classB:
def __init__(self, classA):
self.varA = classA.varA
self.varB = classA.varB
self.varC = classA.varC
(...)
self.varZ = classA.varZ
Is there a better way to make this happen, without going over all the individual attributes?
Upvotes: 0
Views: 383
Reputation: 18106
You could use argument unpacking and inheritance:
class A:
def __init__(self, *args, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
class B(A):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
data = {'varA': 'a', 'varB': 'b', 'varC': 'c'}
a = A(**data)
b = B(**data)
print(a.varB == b.varB)
Out:
True
Upvotes: 1