0
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

1
  • 2
    Change Employee.raise_amount to self.raise_amount and think about it Commented Apr 26, 2020 at 5:38

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It's still a class variable
@MadPhysicist yes. That's why I wrote "that way the lookup of the class variable is done the way you expect it." I only mentiond in a side note, that using an instance variable from the start might lead to a less surprising behaviour.
1

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)

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.