Python中的继承删除原始值

Python中的继承删除原始值,python,Python,我用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 pri

我用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
我遇到的问题是,当我制作两个对象时:

w1=FactoryWorker(2130,4000)
w1.printWage()

prints 4400

w2=OfficeWorker(1244,50,100)
w2.printWage()

prints 5000
但如果我再这样做:

w1.printWage()
它不打印原始的4400,而是打印5000

为什么呢?我希望将可变工资声明为类Worjer的一个属性,而不是在每个子类中单独声明


有什么帮助吗?

您的问题是Worker.wage是类成员,这意味着该类的所有实例将共享相同的值。您需要的只是self.wage,它是实例成员,这意味着类的每个实例都有自己的值。

您似乎知道应该通过self引用实例属性,因为您使用的是payperhour等。所以我不知道您为什么不使用wage


还要注意,super的使用更具python风格和灵活性,而不是显式调用超类。

为什么初始化工厂工人会改变所有工人的基本工资?另外,您可以重新检查您的代码和输出吗?我得到TypeError。您正在更改一个printWage方法中的工资:Worker.wage=self.payperHour*self.numberHours问:我希望可变工资声明为类[Worker]的一个属性,而不是在每个子类中单独声明。@JonSharpe:是,看来OP的要求与他们对系统工作方式的期望不符。
class FactoryWorker(Worker):
    def __init__(self,cod,wage):
        super(FactoryWorker, self).__init__(self,cod,wage)
        self.wage=wage*1.10