[英]python decorator with lazy property
def lazyproperty(func):
name = '_lazy_' + func.__name__
@property
def lazy(self):
print(self)
if hasattr(self, name):
return getattr(self, name)
else:
value = func(self)
setattr(self, name, value)
return value
return lazy
import math
class Circle:
def __init__(self, radius):
self.radius = radius
@lazyproperty
def area(self):
print('Computing area')
return math.pi * self.radius ** 2
我是 python 屬性和裝飾器的新手。 在閱讀上面的一些例子時,我很難理解它是如何工作的。 例如,我不太明白惰性定義中的“自我”如何是 Circle object。有人能詳細說明這個例子嗎? 謝謝!
self
這個名字沒有什么特別之處; 它只是 function 的第一個參數的常規名稱,旨在用作一種方法。 在這種情況下,function 是在lazyproperty
中定義的,而不是直接在 class Circle.
看到在沒有裝飾器語法的情況下編寫相同的代碼可能會有所幫助。
def lazyproperty(func):
name = '_lazy_' + func.__name__
# The "method" to be turned into a property
def lazy(self):
print(self)
if hasattr(self, name):
return getattr(self, name)
else:
value = func(self)
setattr(self, name, value)
return value
# Return the property
return property(lazy)
import math
class Circle:
def __init__(self, radius):
self.radius = radius
# The method to be wrapped by lazyproperty
def area(self):
print('Computing area')
return math.pi * self.radius ** 2
# The actual wrapping to make area a (lazy) property
area = lazyproperty(area)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.