Python 类方法不更改类变量';s值

Python 类方法不更改类变量';s值,python,python-3.x,oop,Python,Python 3.x,Oop,类方法不更改类变量的变量 class Employee: raise_amount = 1.04 def __init__(self,first,last,pay): self.first = first self.last = last self.pay = pay self.email = first+'.'+last+'@company.com' def fullname(self):

类方法不更改类变量的变量

class Employee:

    raise_amount = 1.04


    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 ('{} {}'.format(self.first,self.last))

    def apply_raise(self):
        self.pay = (self.pay * raise_amount)


employee_1=Employee('Bling','Blong',50000)
employee_2=Employee('Test','User',60000)


print (employee_1.pay)
employee_1.apply_raise
print (employee_1.pay)
在我对员工_1应用加薪方法后,下一行应该打印增加的工资。但它仍然显示了50000英镑的旧工资。

在这段代码片段中

 raise_amount = 1.04 
 def __init__(self,first,last,pay):
        self.first = first
        self.last = last
        self.pay = pay
        self.email = first+'.'+last+'@company.com'
self.raise\u amount=1.04
添加到
\u init\u()
并删除
raise\u amount=1.04

self
关键字用于引用类实例,如果没有self,则表示它只是一个局部变量。 在这个功能中,

    def apply_raise(self):
        self.pay = (self.pay * raise_amount)
将变量
raise\u amount
更改为
self.raise\u amount


最后在课外,将
employee\u 1.apply\u raise
更改为
employee\u 1.apply\u raise()


要调用方法,请在结尾使用括号
()

这里您在代码中犯了两个错误: 错误1。在这里

 def apply_raise(self):

    self.pay = (self.pay * raise_amount)
它应该是自我。提高金额

错误2。函数内调用

print (employee_1.pay)

  employee_1.apply_raise

  print (employee_1.pay)
在这里,您应该在employee_1的末尾添加“()”。apply_raise使其成为employee_1。apply_raise()


最初没有调用函数apply\u raise(),因此没有增加值。

employee\u 1.apply\u raise
的末尾没有括号。调用函数时需要括号,否则您只是引用它。
employee\u 1.apply\u raise
不调用该方法当我使用:employee\u 1.apply\u raise()时,我得到一个名错误error:global name“raise\u amount”未定义self.raiseAbout在您的第一条注释中将获得类级别属性的副本。它会起作用,但行为与我认为的有点不同。