python添加、修改、删除、访问类对象属性的2种方法
1.直接添加、修改、删除、访问类对象属性
class Employee (object):
empCount = 0
def __init__(self, name, salary) :
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self) :
print "total employee ",Employee.empCount
def displayEmployee(self) :
print "name :",self.name , ", salary :", self.salary
emp1 = Employee("SR", 10000)
emp1.displayCount()
emp1.displayEmployee()
emp1.salary = 20000
print emp1.salary
emp1.age = 25
print emp1.age
del emp1.age
Employee.empCount=500
print Employee.empCount
Employee.cc="abc"
print Employee.cc
del Employee.empCount
print Employee.empCount
2.使用函数添加、删除、修改、访问类对象属性
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:531509025
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
class Employee(object):
empCount=0
def __init__(self,name,salary):
self.name=name
self.salary=salary
Employee.empCount+=1
def displayCount(self):
print "total employee ",Employee.empCount
def displayEmployee(self):
print "name:",self.name,",salary:",self.salary
emp1=Employee("SR",100000)
if hasattr(emp1,"name"):
print u"属性name存在"
else:
print u"属性name不存在"
try:
a=getattr(emp1,"name")
print u"name属性的值:",a
except Exception,e:
print e
setattr(emp1,"tel","13111111111")
try:
a=getattr(emp1,"tel")
print u"新添加的tel属性的值:",a
except Exception,e:
print e
try:
delattr(emp1,"tel")
except Exception,e:
print e
else:
if hasattr(emp1,"tel"):
print u"属性tel存在"
else:
print u"属性tel不存在"