標籤:用法 mds 命令 als inpu country 基本應用 attribute lex
在學習網路編程的時候用到反射,然後發現自己反射這部分的應用不是很熟練,決定返回來重新整理一下
對於類的反射,主要有四個用法,下面都說一下
1.hasattr 判斷對象或者類是否存在指定的屬性,看代碼以及結果
class people: def __init__(self,name,age): self.name = name self.age = age def talk(self): print("%s is talking."%self.name)p1 = people(‘alex‘,18)print(hasattr(p1,‘name‘))print(hasattr(p1,‘sex‘))結果TrueFalse
hasattr判斷完成後,會返回一個布爾值,有就返回True,無就返回False
2.getattr 擷取到一個對象或者類的屬性,加()就是執行,看代碼
class people: def __init__(self,name,age): self.name = name self.age = age def talk(self): print("%s is talking."%self.name)p1 = people(‘alex‘,18)print(getattr(p1,‘name‘))print(getattr(p1,‘sex‘,‘man‘))print(getattr(p1,‘sex‘))結果alexman File "D:/PycharmProjects/s2018/day6/test.py", line 13, in <module> print(getattr(p1,‘sex‘))AttributeError: ‘people‘ object has no attribute ‘sex‘
對於getattr,如果對象或者是類有輸入的屬性,則,返回正確屬性。無則報錯,如果我們指定預設值,則返回預設值,在看一下其他
class people: def __init__(self,name,age,sex): self.name = name self.age = age self.sex = sex def talk(self): print("%s is talking."%self.name)p1 = people(‘alex‘,18,‘woman‘)getattr(p1,‘talk‘)()#getattr擷取到方法後加()就是執行print(getattr(p1,‘sex‘,‘man‘))#類內如果對屬性已經確認過,顯示對象已經確認的值,而不顯示預設值結果alex is talking.woman
3.setattr 是修改已有的屬性或者是新加一個屬性,看代碼
class people: def __init__(self,name,age,sex): self.name = name self.age = age self.sex = sex def talk(self): print("%s is talking."%self.name)p1 = people(‘alex‘,18,‘woman‘)print(‘修改前‘,p1.age)setattr(p1,‘age‘,20)print(‘修改後‘,p1.age)setattr(p1,‘country‘,‘China‘)print(p1.__dict__)結果修改前 18修改後 20{‘country‘: ‘China‘, ‘name‘: ‘alex‘, ‘sex‘: ‘woman‘, ‘age‘: 20}
4.delattr就是對現有的對象或者類的屬性就行刪除,這個比較簡單,看代碼
class people: def __init__(self,name,age,sex): self.name = name self.age = age self.sex = sex def talk(self): print("%s is talking."%self.name)p1 = people(‘alex‘,18,‘woman‘)print(‘修改前‘,p1.__dict__)delattr(p1,‘name‘)print(‘修改後‘,p1.__dict__)結果修改前 {‘age‘: 18, ‘name‘: ‘alex‘, ‘sex‘: ‘woman‘}修改後 {‘age‘: 18, ‘sex‘: ‘woman‘}
5.學會基本的,還是需要一些應用才可以,寫一個比較的應用,正好也是我在網路編程中需要的,看代碼
class Servers:#定義一個伺服器類 def run(self):#定義方法run while True: cmds = input(">>>>:").strip().split()#將輸入的命令列進行分解,分解成前面命令以及後面的檔案名稱 if hasattr(self,cmds[0]):#判斷是否有命令! func = getattr(self,cmds[0])#如果命令存在則執行 func(cmds) else: print(‘你的輸入錯誤!‘) continue def get(self,cmds):#示範 print(‘get.....‘,cmds[1]) def put(self,cmds):#示範 print(‘put.....‘,cmds[1])obj = Servers()obj.run()結果>>>>:get a.txtget..... a.txt>>>>:put a.txtput..... a.txt>>>>:gett a你的輸入錯誤!>>>>:
以上就是類的反射的一些基本應用,任何知識都是基本簡單,組合難,就看大家如何組合了,後面又想到其他想法,也會再去更新這個
2018.6.18
python學習之類的反射(2018.6.18)