通過字符串的形式操作對(duì)象的相關(guān)屬性。
方法有hasattr,getattr,delattr創(chuàng)新互聯(lián)-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價(jià)比威海網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式威海網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋威海地區(qū)。費(fèi)用合理售后完善,10年實(shí)體公司更值得信賴。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
class People:
country='China'
def __init__(self,name,age):
self.name=name
self.age=age
def talk(self):
print('%s is talking' %self.name)
obj=People('egon',18)
print(obj.name) #obj.__dict__['name']
print(obj.talk)
choice='name'
# 這樣直接使用字符串是不可以的,報(bào)錯(cuò)信息 AttributeError: 'People' object has no attribute 'choice'
# print(obj.choice) #print(obj.'name')
#但是反射,可以通過字符串操作對(duì)象中的屬性
print("hasattr(obj,'name')===",hasattr(obj,'name')) #等同obj.name #obj.__dict__['name']
print("hasattr(obj,'talk')===",hasattr(obj,'talk')) #等同#obj.talk
print("hasattr(obj,'talk12')===",hasattr(obj,'talk12'))
print("getattr(obj,'namexxx',None)===",getattr(obj,'namexxx',None))
print("getattr(obj,'talk',None)===",getattr(obj,'talk',None))
setattr(obj,'sex','male') #obj.sex='male'
print("setattr(obj,'sex','male')===",obj.sex)
delattr(obj,'age') #del obj.age
print("delattr(obj,'age')===",obj.__dict__)
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
egon
>
hasattr(obj,'name')=== True
hasattr(obj,'talk')=== True
hasattr(obj,'talk12')=== False
getattr(obj,'namexxx',None)=== None
getattr(obj,'talk',None)=== >
setattr(obj,'sex','male')=== male
delattr(obj,'age')=== {'name': 'egon', 'sex': 'male'}
Process finished with exit code 0
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
#反射的應(yīng)用:
class Service:
def run(self):
while True:
inp=input('>>: ').strip() #cmd='get a.txt'
cmds=inp.split() #cmds=['get','a.txt']
# print(cmds)
if hasattr(self,cmds[0]):
func=getattr(self,cmds[0])
func(cmds)
def get(self,cmds):
print('get.......',cmds)
def put(self,cmds):
print('put.......',cmds)
obj=Service()
obj.run()
print("getattr(obj,'namexxx',None)===",getattr(obj,'namexxx',None))
print("getattr(obj,'talk',None)===",getattr(obj,'talk',None))
setattr(obj,'sex','male') #obj.sex='male'
print("setattr(obj,'sex','male')===",obj.sex)
delattr(obj,'age') #del obj.age
print("delattr(obj,'age')===",obj.__dict__)
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
>>: get a.txt
get....... ['get', 'a.txt']
__getitem__ obj['name']像字典一樣調(diào)用屬性的時(shí)候會(huì)觸發(fā)__getitem__執(zhí)行
__setitem__ obj['age']=22像字典一樣設(shè)置屬性的時(shí)候會(huì)觸發(fā)__setitem__執(zhí)行
__delitem__ del obj['age']像字典一樣刪除屬性的時(shí)候會(huì)觸發(fā)__delitem__執(zhí)行
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
class Foo: #Dict
def __init__(self,name):
self.name=name
def __getitem__(self, item):
print('getitem...self.__dict__.get(%s)'%item)
# 這里不返回,obj['name']是不會(huì)獲取到值的,因?yàn)檫@樣操作就是執(zhí)行__getitem__方法
return self.__dict__.get(item)
def __setitem__(self, key, value):
print("setitem...self.__dict__[%s]=%s"%(key,value))
self.__dict__[key]=value
def __delitem__(self, key):
print("delitem...del self.__dict__[%s]"%key)
del self.__dict__[key]
obj=Foo('egon')
# 查看屬性
print(obj.__dict__)
# getitem觸發(fā)時(shí)機(jī):obj['name']像字典一樣調(diào)用屬性的時(shí)候,會(huì)觸發(fā)
print("obj['name']",obj['name']) #結(jié)果egon
print("obj['namexx']",obj['namexx']) # 沒有,返回None
print("obj.name",obj.name) # 這樣不會(huì)觸發(fā)__getitem__,必須讓字典一樣操作才會(huì)觸發(fā)
#設(shè)置屬性
obj.sex='male' #這樣不會(huì)觸發(fā)__setitem__,但也能給對(duì)象添加數(shù)據(jù)屬性
print("obj.sex='male'====",obj.__dict__)
print("obj.sex======",obj.sex)
obj["age"]=22
print("obj['age']=22======",obj.__dict__)
print("obj.age======",obj.age) #設(shè)置后,可以直接使用對(duì)象來獲取數(shù)據(jù)屬性
#刪除屬性
del obj.sex #這樣不會(huì)觸發(fā)__del__item
print("del obj.sex====",obj.__dict__)
del obj['age']
print("del obj['age']====",obj.__dict__)
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
{'name': 'egon'}
getitem...self.__dict__.get(name)
obj['name'] egon
getitem...self.__dict__.get(namexx)
obj['namexx'] None
obj.name egon
obj.sex='male'==== {'name': 'egon', 'sex': 'male'}
obj.sex====== male
setitem...self.__dict__[age]=22
obj['age']=22====== {'name': 'egon', 'sex': 'male', 'age': 22}
obj.age====== 22
del obj.sex==== {'name': 'egon', 'age': 22}
delitem...del self.__dict__[age]
del obj['age']==== {'name': 'egon'}
Process finished with exit code 0
"isinstance(obj,cls)檢查是否obj是否是類 cls 的對(duì)象"
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
class Foo(object):
pass
obj = Foo()
print(isinstance(obj, Foo))
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
True
Process finished with exit code 0
"issubclass(sub, super)檢查sub類是否是 super 類的派生類"
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
class Foo(object):
pass
class Bar(Foo):
pass
print(issubclass(Bar, Foo))
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
True
Process finished with exit code 0
"沒有設(shè)置這兩個(gè)方法時(shí)"
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
class School:
def __init__(self,name,addr,type):
self.name=name
self.addr=addr
self.type=type
s1=School('oldboy1','北京','私立')
print('from repr: ',repr(s1))
print('from str: ',str(s1))
print(s1)
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
from repr: <__main__.School object at 0x000001CC930BEAC8>
from str: <__main__.School object at 0x000001CC930BEAC8>
<__main__.School object at 0x000001CC930BEAC8>
Process finished with exit code 0
"可以顯式調(diào)用repr和str方法,
repr和str方法同時(shí)存在時(shí),會(huì)優(yōu)先調(diào)用str方法,
str方法沒有時(shí),會(huì)調(diào)用repr方法
repr和str方法都是在print(obj)時(shí)調(diào)用的,沒有這兩個(gè)方法,輸出的是對(duì)象的內(nèi)存地址,有了這兩個(gè)方法,就可以自行設(shè)置有意義的輸出"
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
class School:
def __init__(self,name,addr,type):
self.name=name
self.addr=addr
self.type=type
def __repr__(self):
return 'School(%s,%s)' %(self.name,self.addr)
def __str__(self):
return '(%s,%s)' %(self.name,self.addr)
s1=School('oldboy1','北京','私立')
# 可以顯式調(diào)用repr和str方法
print('from repr: ',repr(s1))
print('from str: ',str(s1))
print('from repr: ',s1.__repr__())
print('from str: ',s1.__str__())
print(s1)
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
from repr: School(oldboy1,北京)
from str: (oldboy1,北京)
from repr: School(oldboy1,北京)
from str: (oldboy1,北京)
(oldboy1,北京)
Process finished with exit code 0
"程序正常結(jié)束后,或回收系統(tǒng)資源時(shí)如f.close(),會(huì)調(diào)用__del__"
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
class Open:
def __init__(self,filename):
print('open file.......')
self.filename=filename
def __del__(self):
print('回收操作系統(tǒng)資源:self.close()')
f=Open('settings.py')
print('----main------')
"手動(dòng)del,會(huì)提前執(zhí)行__del__"
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
class Open:
def __init__(self,filename):
print('open file.......')
self.filename=filename
def __del__(self):
print('回收操作系統(tǒng)資源:self.close()')
f=Open('settings.py')
#程序結(jié)束的時(shí)候,會(huì)自動(dòng)del f 回收f,就會(huì)執(zhí)行__del__
del f # 如果沒有這行代碼,會(huì)先執(zhí)行print(--main--),之后回收f,運(yùn)行__del__,如果手動(dòng)在這里del,就會(huì)先執(zhí)行__del__,然后執(zhí)行后面語句
print('----main------')
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
open file.......
回收操作系統(tǒng)資源:self.close()
----main------
Process finished with exit code 0