python類的裝飾器
- 2019 年 10 月 5 日
- 筆記
版權聲明:本文為部落客原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。
本文鏈接:https://blog.csdn.net/weixin_36670529/article/details/100581574
我們知道,在不改變原有程式碼的基礎上,我們可以使用裝飾器為函數添加新的功能。同理,一切皆對象,我們也可以使用裝飾器為類添加類屬性。
def deco(obj): obj.x = 1 obj.y = 2 return obj @deco # Foo = deco(Foo) class Foo: pass print(Foo.__dict__)
上述的程式碼為Foo屬性字典添加了x和y屬性,但如果想添加'name' = 'harden'呢,這需要更靈活的定義了。
def deco(**kwargs): def wrapper(obj): for k, v in kwargs.items(): setattr(obj, k, v) return obj return wrapper @deco(x=1, y=2) class Foo: pass print(Foo.__dict__) Output: --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- {'__module__': '__main__', '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': None, 'x': 1, 'y': 2} ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
我們再定義類Bar,
@deco(name='curry') class Bar: pass
name屬性也可以添加進去
再來個升級版,利用數據描述符和類的裝飾器為類屬性限定數據類型。我們知道,在不改變原有程式碼的基礎上,我們可以使用裝飾器為函數添加新的功能。同理,一切皆對象,我們也可以使用裝飾器為類添加類屬性。
def deco(obj): obj.x = 1 obj.y = 2 return obj @deco # Foo = deco(Foo) class Foo: pass print(Foo.__dict__) 上述的程式碼為Foo屬性字典添加了x和y屬性,但如果想添加'name' = 'harden'呢,這需要更靈活的定義了。so def deco(**kwargs): def wrapper(obj): for k, v in kwargs.items(): setattr(obj, k, v) return obj return wrapper @deco(x=1, y=2) class Foo: pass print(Foo.__dict__) {'__module__': '__main__', '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': None, 'x': 1, 'y': 2} 我們再定義類Bar, @deco(name='curry') class Bar: pass name屬性也可以添加進去 再來個升級版,利用數據描述符和類的裝飾器為類屬性限定數據類型 #數據描述符,代理另一個新式類的屬性 class Typedef: def __init__(self, key, expected_type): self.key = key self.expected_type = expected_type def __get__(self, instance, owner): # print('exec __get__') # print(instance) # print(owner) return instance.__dict__[self.key] def __set__(self, instance, value): # print('exec __set__') if not isinstance(value, self.expected_type): raise TypeError instance.__dict__[self.key] = value def __delete__(self, instance): instance.__dict__.pop(self.key) def deco(**kwargs): def wrapper(obj): for k, v in kwargs.items(): #為obj添加屬性 如 name = Tpyedef('name', str) setattr(obj, k, Typedef(k, v)) return obj return wrapper @deco(name=str, age=int, salary=float) # =====》People= wrapper(People) class People: def __init__(self, name, age, salary): self.name = name self.age = age self.salary = salary p1 = People('handen', 18, 111.11) print(p1.name) print(p1.__dict__)