Python - 设置对象的属性

时间:2015-12-09 12:33:32

标签: python class attributes

我被要求在程序中添加一个属性。该属性用于显示Zara新工资3000的变化。

我被要求将其添加为setattr(obj,name,value)函数,以便为Zara设置新工资。

这是我的代码:

__author__ = 'SWA14096171'

class Employee:

    empCount = 0

    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
        Employee.empCount +=1

    def displayCount (self):
        print('total employee %d') % Employee.empCount

    def displayEmployee (self) :
        print (' Name : ', self.name, ', Salary: ', self.salary)

emp1 = Employee('Zara', 2000)

emp2 = Employee (' Manni', 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print ('Total Employee %d' % Employee.empCount)

1 个答案:

答案 0 :(得分:0)

不要担心。它很简单:

emp1.salary = 3000

如果要更改属性的值,只需为其指定新值即可。然后你可以按照自己的意愿打印出来。

print emp1.salary    #just salary
print "%s's salary is %d" % (emp1.name, emp1.salary)  #salary and name
emp1.displayEmployee()   # using your method

希望有所帮助!