標籤:
#coding=utf-8class 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, "\nSalary: ", self.salary)Xiaoxiao = Employee(‘Xiaoxiao‘, 2000)setattr(Xiaoxiao, ‘age‘, 21)Tiny = Employee("Tiny", 5000)#setattr(Tiny, ‘age‘, 23)print ("執行個體 Employee 類的第一個對象 Xiaoxiao ");print (‘Xiaoxiao 是否存在age屬性:‘,hasattr(Xiaoxiao,‘age‘))Xiaoxiao.displayEmployee(); print("Age: ",getattr(Xiaoxiao,‘age‘, ‘not find‘));print ("\n")print ("執行個體 Employee 類的第二個對象 Tiny")print (‘Tiny 是否存在age屬性:‘,hasattr(Tiny,‘age‘))Tiny.displayEmployee()print("Age: ",getattr(Tiny,‘age‘, ‘not find‘));print ("\n")print ("Total Employee number: %d" % Employee.empCount)print ("\n")
Python 類 setattr、getattr、hasattr 的使用