Reputation: 63
class Employee:
raise_amount = 1.02
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first+'.'+last+'@company.com'
def fullname(self):
return f"Full name is {self.first} {self.last}"
def apply_raise(self):
self.pay = int(self.pay * Employee.raise_amount)
class Developer(Employee):
raise_amount = 1.10
dev1 = Developer('Test1','User1',20000)
dev2 = Developer('Test2','User2',25000)
print(dev1.pay)
dev1.apply_raise()
print(dev1.pay)
O/p : 20000 20400
where as the o/p should have been 20000 22000
22000, Because we are overriding the class variable in the subclass
what is that which im doing wrong here
Upvotes: 0
Views: 51
Reputation: 10782
You should change
self.pay = int(self.pay * Employee.raise_amount)
to
self.pay = int(self.pay * self.raise_amount)
that way, the lookup of the class variable is done the way you expect it.
It will all be less confusing if you use a instance variable instead of a class variable to achieve what you want.
Upvotes: 2
Reputation: 75
def apply_raise(self): self.pay = int(self.pay * Employee.raise_amount)
try replacing Employee with self
def apply_raise(self): self.pay = int(self.pay * self.raise_amount)
Upvotes: 0
Reputation: 77337
You create a subclass but the parent uses Employee.raise_amount
for calculations, hard coding the class. Change that to self.raise_amount
so that the parent method will use the subclass variable instead.
def apply_raise(self):
self.pay = int(self.pay * self.raise_amount)
Upvotes: 1