在 Python 中创建实例对象
要创建类的实例,使用类名调用类并传递其 __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, name[, default]) − 访问对象的属性。
- hasattr(obj,name) − 检查属性是否存在。
- setattr(obj,name,value) − 设置属性。如果属性不存在,则会创建它。
- delattr(obj, name) − 删除属性。
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'
了解有关 Python 面向对象特性的更多信息: Python 类和对象教程
广告