I have programmed a small inheritance problem in Python:
class Worker:
def __init__(self,cod):
self.cod=cod
self.wage=0
class FactoryWorker(Worker):
def __init__(self,cod,wage):
Worker.__init__(self,cod,wage)
Worker.wage=wage*1.10
def printWage(self):
return Worker.wage
class OfficeWorker(Worker):
def __init__(self,cod,payperHour,numberHours):
Worker.__init__(self,cod)
self.payperHour=payperHour
self.numberHours=numberHours
def printWage(self):
Worker.wage=self.payperHour*self.numberHours
return Worker.wage
The problem that I have is when I make a couple of objects:
w1=FactoryWorker(2130,4000)
w1.printWage()
prints 4400
w2=OfficeWorker(1244,50,100)
w2.printWage()
prints 5000
but if I do again:
w1.printWage()
it does not print the original 4400, but it prints instead 5000
why is that? I want the variable wage to be declared as an attribute of the class Worjer and not individually in each one of the subclasses.
Any help?
Your problem is that Worker.wage
is a class member, meaning that all instances of the class will share the same value. What you want is simply self.wage
, which is an instance member, meaning that each instance of the class will have its own value.
You appear to know that you should refer to instance attributes via self
, since you are doing that with payperhour
etc. So I don't know why you aren't also doing it with wage
.
class FactoryWorker(Worker):
def __init__(self,cod,wage):
super(FactoryWorker, self).__init__(self,cod,wage)
self.wage=wage*1.10
(Also note the more Pythonic and flexible use of super
, rather than calling the superclass explicitly.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.