繫結方法與非繫結方法, 反射
阿新 • • 發佈:2020-12-23
目錄
繫結方法與非繫結方法, 反射
繫結方法與非繫結方法
在類內部定義的函式, 分為兩大類:
-
繫結方法: 繫結給誰, 就應該由誰來呼叫, 誰來呼叫就會把呼叫者當做第一個引數自動傳入
繫結到物件的方法: 在類內部定義的沒有任何裝飾器修飾的
繫結到類的方法, 使用classmethod裝飾器修飾
-
非繫結方法: 不與類或者物件繫結
import settings class People: def __init__(self,name,age,sex): self.name=name self.age=age self.sex=sex def tell_info(self): print("name:%s, age:%s, sex:%s" %(self.name,self.age,self.sex)) @classmethod #繫結方法到類, 不需要例項化, 直接呼叫, People.from_conf() def from_conf(cls): obj=cls(settings.name,settings.age,settings.sex) return obj @staticmethod #非繫結方法, 不強制給方法傳參 def create_id(): m=hashlib.md5(str(time.time()).encode('utf-8')) return m.hexdigest() # settings content # name='wtp' # age=30 # sex='male' # p=People('egon',18,'male') # p.tell_info() # name:egon, age:18, sex:male # p=People.from_conf() # p.tell_info() # name:wtp, age:30, sex:male
反射
class test: def __init__(self,name): self.name1=name def name(self,age): print(age) print(self.name1) t=test('wtp') choice='name' print(hasattr(t,choice)) #判斷物件t是否有name屬性或方法 a=getattr(t,choice,None) #如果物件t有屬性或方法name, 則獲取屬性name的值或者方法, 如果沒有, 則返回None a(18) # 輸出 # 18 # wtp delattr(t,choice) #刪除物件t的屬性choice print(getattr(t,choice)) setattr(t,'age',18) #為物件t增加屬性age print(t.age)
class Service: def run(self,cmds): func=cmds.split() if hasattr(self,func[0]): a=getattr(self,func[0]) a(cmds) def get(self,cmds): print('run ',cmds) def put(self,cmds): print('run ',cmds) s=Service() s.run('get txt') # run get txt s.run('put txt') # run put txt