要创建类的实例,请使用类名称调用该类,然后传递其__init__方法接受的任何参数。
"This would create first object of Employee class" emp1 = Employee("Zara", 2000) "This would create second object of Employee class" emp2 = Employee("Manni", 5000)
您可以使用带点运算符和对象来访问对象的属性。将使用类名称访问类变量,如下所示:
emp1.displayEmployee() emp2.displayEmployee() print "Total Employee %d" % Employee.empCount
现在,将所有概念放在一起-
#!/usr/bin/python class Employee: 'Common base class for all employees' 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 "This would create first object of Employee class" emp1 = Employee("Zara", 2000) "This would create second object of Employee class" emp2 = Employee("Manni", 5000) emp1.displayEmployee() emp2.displayEmployee() print "Total Employee %d" % Employee.empCount
输出结果
执行以上代码后,将产生以下结果-
Name : Zara ,Salary: 2000 Name : Manni ,Salary: 5000 Total Employee 2
您可以随时添加,删除或修改类和对象的属性-
emp1.age = 7 # Add an 'age' attribute. emp1.age = 8 # Modify 'age' attribute. del emp1.age # Delete 'age' attribute.
可以使用以下功能代替使用普通语句访问属性:
GETATTR(OBJ,名称[,默认]) -访问对象的属性。
该hasattr(OBJ,名) -检查一个属性存在与否。
该SETATTR(OBJ,名称,值) -设置属性。如果属性不存在,则将创建它。
该delattr(OBJ,名) -删除一个属性。
hasattr(emp1, 'age') # Returns true if 'age' attribute exists getattr(emp1, 'age') # Returns value of 'age' attribute setattr(emp1, 'age', 8) # Set attribute 'age' at 8 delattr(empl, 'age') # Delete attribute 'age'