1、反射
用字符串来操作类或者对象的属性
class People: # country= 'china' # def __init__(self,name): # self.name= name # # def eat(self): # print('%s is eating'%(self.name)) # peo1= People ('qqc') (1)hasattr print(hasattr(peo1,'name')) #判断name是否在peo1.name中是可以访问的属性
(2)getarrt
print(getattr(peo1,'xx','None'))#在peo1中没有xx这个属性,返回None,不会报错 (3)strattr
setattr(peo1,'age',19) #增加属性 # print(peo1 .__dict__ ) (4)delattr(peo1,'name') #删除
2、1.内置方法__str__
class People: # # def __init__(self,name,age): # # self.name = name # # self.age= age # # #在对象self被打印时,自动触发 ,应该在方法内采集与对象self有关的信息,然后拼成字符串返回 # # def __str__(self): # # return '姓名%s,年龄%s'%(self.name,self .age) # # # # obj = People ('qqc',33) # # print(obj)
2、2.内置方法__del__
__del__析构方法 # class People: # def __init__(self,name,age): # self.name = name # self.age= age # self.f= open('q.txt','rt',encoding= 'utf-8') # def __del__(self): # #做回收系统资源相关的事情 # self.f.close() # print('ggg') # # obj = People('egon',18) # del obj