简体   繁体   English

具有惰性属性的 python 装饰器

[英]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

I am new to python property and decorators.我是 python 属性和装饰器的新手。 When reading some examples like above, I have difficulty understanding how it works.在阅读上面的一些例子时,我很难理解它是如何工作的。 For example, I do not quite get how the "self" inside the lazy definition is the Circle object.Could any one elaborate this example?例如,我不太明白惰性定义中的“自我”如何是 Circle object。有人能详细说明这个例子吗? Thanks!谢谢!

There is nothing special about the name self ; self这个名字没有什么特别之处; it's just the conventional name given to the first parameter of a function intended to be used as a method.它只是 function 的第一个参数的常规名称,旨在用作一种方法。 In this case, that function is defined inside lazyproperty instead of directly in the class Circle.在这种情况下,function 是在lazyproperty中定义的,而不是直接在 class Circle.

It might help to see the same code written without decorator syntax.看到在没有装饰器语法的情况下编写相同的代码可能会有所帮助。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM