標籤:運行 定製 port 傳回值 就是 裝飾器 tar key elf
__slots__ 限制 執行個體添加額外屬性
了達到限制的目的,Python允許在定義class的時候,定義一個特殊的__slots__變數,來限制該class執行個體能添加的屬性:
class Student(object): __slots__ = (‘name‘,‘age‘) # 用tuple定義允許綁定的函數名字
使用 __slots__ 要注意 __slots__ 定義的屬性 僅對 當前類執行個體起作用 對 繼承的子類不起作用
class GraduateStudent(Student): passg = GraduateStudent()g.score = 9999 # 繼承的子類可以 實現修改#除非在子類中也定義__slots__,這樣,子類執行個體允許定義的屬性就是自身的__slots__加上父類的__slots__。
@property
Python內建的@property裝飾器就是負責把一個方法變成屬性調用
class Room: def __init__(self,name,width,length): self.name=name self.width=width self.length=length @property def area(self): return self.width * self.lengthr1=Room(‘alex‘,1,1)print(r1.area)
定製類Python 的 class有很多 特殊用的後漢書來幫我們定製類
__str__ __repr__
# 定義一個Student類 列印一個執行個體class Student(object): def __init__(self, name): self.name = nameprint(Student(‘Micheal‘))
<__main__.Student object at 0x00000000028D1128> #__str__ 方法就是為了讓這一行更加清晰
常用 __str__ __repr__用法是 組合起來用
class Student(object): def __init__(self, name): self.name = name def __str__(self): return ‘Student object (name=%s)‘ % self.name __repr__ = __str__
‘‘‘str函數或者print函數--->obj.__str__()repr或者互動式解譯器--->obj.__repr__()如果__str__沒有被定義,那麼就會使用__repr__來代替輸出注意:這倆方法的傳回值必須是字串,否則拋出異常‘‘‘
Python式的 getter setter也是用 property實現的
class Foo: @property: def AAA(self): print(‘get用這個‘) @AAA.setter def AAA(self,value): print(‘set 用這個‘)#只有在屬性AAA定義property後才能定義AAA.setterf1 = Foo()f1.AAA # 調用getf1.AAA=‘AAAasd1‘ #調用 set
另一種實現形式 是 __getattr__ __setattr__()
class Foo: x=1 def __init__(self,y): self.y=y def __getattr__(self, item): print(‘----> from getattr:你找的屬性不存在‘) def __setattr__(self, key, value): print(‘----> from setattr‘) # self.key=value #這就無限遞迴了,你好好想想 # self.__dict__[key]=value #應該使用它#__setattr__添加/修改屬性會觸發它的執行f1=Foo(10)print(f1.__dict__) # 因為你重寫了__setattr__,凡是賦值操作都會觸發它的運行,你啥都沒寫,就是根本沒賦值,除非你直接操作屬性字典,否則永遠無法賦值f1.z=3print(f1.__dict__)#__getattr__只有在使用點調用屬性且屬性不存在的時候才會觸發f1.xxxxxx
__call__ 當我們調用執行個體方法時 或許會 使用 isinstance(obj)調用 也可以 使用 __call__方式 使用
枚舉類的用法
from enum import Enumclass Gender(Enum): Male = 0 Female = 1class Student(object): def __init__(self, name, gender): self.name = name self.gender = genderbart = Student(‘Bart‘, Gender.Male)
元類 的 內容暫時理解很模糊 通讀了一遍 廖雪峰老師的 元類介紹
https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014319106919344c4ef8b1e04c48778bb45796e0335839000
Python物件導向高階