简体   繁体   中英

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. 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? Thanks!

There is nothing special about the name self ; it's just the conventional name given to the first parameter of a function intended to be used as a method. In this case, that function is defined inside lazyproperty instead of directly in the 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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