I'm trying to learn and understand how to use super in Python, Ive been following the book 'Python journey from novice to expert' and although I feel that I understand the concept Im having problems executing super in my own code.
For example, this method works for me:
class Employee:
def __init__(self, firstname, lastname, age, sex, dob):
self.firstname = firstname
self.lastname = lastname
self.age = age
self.sex = sex
self.dob = dob
self.all_staff.append(self)
class Hourly(Employee):
def __init__(self, firstname, lastname, age, sex, dob, rate, hours):
self.rate = rate
self.hours = hours
super().__init__(firstname, lastname, age, sex, dob)
def __str__(self):
return "{} {}\nAge: {}\nSex: {}\nDOB: {}\n".format(self.firstname, self.lastname, self.age,
self.sex, self.dob)
def get_rate(self):
print('The hourly rate of {} is {} '.format(self.firstname, self.rate))
hourlystaff1 = Hourly('Bob', 'Foo', '23', 'M', '12/1/1980', '$15', '30')
print(hourlystaff1)
print(hourlystaff1.get_rate())
returns the following:
Bob Foo
Age: 23
Sex: M
DOB: 12/1/1980
The hourly rate of Bob is $15
None
This is what I expected (I'm not sure why 'None' is also being returned though, perhaps someone can explain?).
And then I wanted to try this using super but with **kwargs like so:
class Employee:
def __init__(self, firstname='', lastname='', age='', dob='', **kwargs):
super().__init__(**kwargs)
self.firstname = firstname
self.lastname = lastname
self.age = age
self.dob = dob
class Hourly(Employee):
def __init__(self, rate=''):
self.rate = rate
super().__init__(**kwargs)
def __str__(self):
return "{} {}\nAge: {}\nSex: {}".format(self.firstname, self.lastname, self.age,
self.sex, self.dob, self.rate)
def get_rate(self):
print('The hourly rate of {} is {} '.format(self.firstname, self.rate))
bob = Hourly('Bob', 'Bar', '23', '12/1/2019')
bob.get_rate('$12')
returns this error:
File "staff_b.py", line 33, in <module>
bob = Hourly('Bob', 'Bar', '23', '12/1/2019')
TypeError: __init__() takes from 1 to 2 positional arguments but 5 were given
what am I doing wrong in this second approach? How can I use **kwargs and super correctly here?
Edit:
this is a screenshot of an example from the book which I have been following:
what is different between how I use **kwargs and super in my second example to there?
This is also a comprehensive case study from the same book and chapter. This works for me and I understand how it works but I dont seem to be able to translate it into my own work.