访问属性
您可以使用点号 . 来访问对象的属性。使用如下类的名称访问类变量:
emp1.displayEmployee()
emp2.displayEmployee()
print"Total Employee %d"%Employee.empCount
完整实例:
实例
#!/usr/bin/python# -*- coding: UTF-8 -*-classEmployee: '所有员工的基类' empCount = 0 def__init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 defdisplayCount(self): print"Total Employee %d" % Employee.empCount defdisplayEmployee(self): print"Name : ", self.name, ", Salary: ", self.salary"创建 Employee 类的第一个对象"emp1 = Employee("Zara", 2000)"创建 Employee 类的第二个对象"emp2 = Employee("Manni", 5000)emp1.displayEmployee()emp2.displayEmployee()print"Total Employee %d" % Employee.empCount
执行以上代码输出结果如下:
Name: Zara,Salary: 2000
Name: Manni,Salary: 5000
TotalEmployee2