在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 类与对象教程