Reputation: 603
I have a class with a bunch of generic variables in the init method not specific to the class. I want to make another class that holds these variables and then have the first class inheritance those variables.
So the second class is not a parent class, but more like a module class.
How I write this in python?
Thanks.
Class A():
def __init__(self):
self.generic_variable1 = 'blah'
self.generic_variable2 = 'blah'
self.generic_variable3 = 'blah'
self.generic_variable4 = 'blah'
self.generic_variable5 = 'blah'
self.generic_variable6 = 'blah'
def generic_method1(self):
return 'blah'
def class_specific_method1(self):
pass
After creating two classes:
Class A():
def __init__(self):
pass
def class_specific_method1(self):
pass
Class B():
def __init__(self):
self.generic_variable1 = 'blah'
self.generic_variable2 = 'blah'
self.generic_variable3 = 'blah'
self.generic_variable4 = 'blah'
self.generic_variable5 = 'blah'
self.generic_variable6 = 'blah'
def generic_method1(self):
return 'blah'
Upvotes: 0
Views: 51
Reputation: 23753
A module level dictionary that the class can access.
d = {'k':'v','q':'r','m':'n',...}
class F:
variables = d
def __init__(self,...)
Or maybe a collections.namedtuple instead of a dictionary to give you dot access - instance.variables.attr
instead of instance.variables[attr]` .
If you want individual attributes:
d = {'k':'v','q':'r','m':'n'}
class F:
def __init__(self):
for attr,val in d.items():
setattr(self,attr,val)
Or set the attributes outside of the class
d = {'k':'v','q':'r','m':'n'}
class F:
def __init__(self):
pass
for k,v in d.items():
setattr(F,k,v)
Upvotes: 1
Reputation: 1087
Just simply
class A:
... ...
class B(A):
... ...
In class B, if you do not rewrite __init__
, it will automatically use class A's.
If you need do extra thing in class B's __init__
:
class B(A):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
... ...
Upvotes: 1