If I have this parent class to define a profile:
class Profile:
# this is the class constructor
def __init__(self, account_holder, account_type, value):
self.account_holder = account_holder
self.account_type = account_type
self.value = value
# some methods for the user account:
def info(self):
print(self.account_holder)
print(self.account_type)
print(self.value)
# create object:
personal_acc = Profile(account_holder='Me',
account_type='main account',
value= 100)
personal_acc.info()
Now if I make a child class which is simply a business user profile - this inherits all the attributes of the parent class:
class Business(Profile):
# this is a child class:
def __init__(self, business_name, business_value = 100):
self.business_name = business_name
self.business_value = business_value
# new_method
def increase_value(self, increase = 400):
self.business_value += increase
meta = Business(business_name='whatsapp', business_value = 1000)
meta.increase_value()
print(meta.business_value)
# print a method of the parent class using child class Business:
meta.info()
when i run the last line of meta.info()
I get this error message:
Traceback (most recent call last): File "c:\Users\beans\test.py", line 558, in meta.info() File "c:\Users\beans\test.py", line 523, in info print(self.account_holder) AttributeError: 'Business' object has no attribute >'account_holder'
How do i pass in the attribute account_holder
, account_type
and value
when I create my user sub class?
Or should I set default values for these?
You still need to call the parent's __init__
method to initialize those attributes not defined explicitly by Business
. This means Business.__init__
still needs to accept the appropriate arguments to pass to the inherited __init__
, something that is typically best done by using keyword arguments so that it's easier (or even possible, in the case of multiple inheritance) to determine which arguments need to be passed on.
class Profile:
# this is the class constructor
def __init__(self, *, account_holder, account_type, value, **kwargs):
super().__init__(**kwargs)
self.account_holder = account_holder
self.account_type = account_type
self.value = value
class Business(Profile):
# this is a child class:
def __init__(self, *, business_name, business_value, **kwargs):
super().__init__(**kwargs)
self.business_name = business_name
self.business_value = 100
# new_method
def increase_value(self, increase = 400):
self.business_value += increase
meta = Business(account_holder="...", account_type="...", value=..., business_name='whatsapp', business_value = 1000)