【问题标题】:Problems with multiplying a class variable with an instance将类变量与实例相乘的问题
【发布时间】:2021-12-02 09:32:09
【问题描述】:

我是 pyhton 的新手,也是使用类的新手。我正在解决以下问题,我想将类变量(raise_amount)乘以实例薪水。但是,当我这样做时,我得到 None 作为输出。我想得到每人的工资乘以 1.04。任何帮助将不胜感激。

class Person:
        
    raise_amount = 1.04
    
    def __init__(self, name, street_name, house_nr, post_code, salary): #:post_code, salary):
        self.name = name
        self.street_name = street_name
        self.house_nr = house_nr
        self.post_code = post_code
        self.salary = salary
        
  
    def street_name_and_house_nr(self):
        return '{} {}'.format(self.street_name, self.house_nr)

    
    def apply_raise(self):      # here is the code that seems to have problems 
        self.salary =  int(Person.raise_amount * self.salary)
    
    def street_name_and_house_nr_salary(self):
        return self.name + ' ' + str(self.salary)
        
prs_1 = Person("Mary's", 'Broadway', 304, '2526 CG', 10) 
prs_2 = Person("Jhon's", 'Longstreet', 304, '2829 AK',7) 
prs_3 = Person("Larry's", 'Chinstreet', 58, '3046 JP', 8) 

print(Person.apply_raise(prs_1))
print(Person.apply_raise(prs_2))
print(Person.apply_raise(prs_3))

这是我运行代码时得到的输出

None
None
None

【问题讨论】:

    标签: python class instance-variables


    【解决方案1】:

    apply_raise() 不返回新的薪水,它只是更新薪水属性。所以你应该把它单独打印出来。

    prs_1.apply_raise()
    print(prs_1.salary)
    

    其他说明:

    1. 通常方法的第一个参数是self。不要编自己的名字(lelf 是什么意思?)。
    2. 您应该使用instance.method() 调用方法,而不是Class.method(instance)。这样可以确保当实例位于子类中时使用正确的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-21
      • 2011-06-10
      • 2013-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多