简体   繁体   中英

Get property name when using @property decorator

Let's take this piece of code.

class property_name(object):
    def __init__(self, function):
        self.property_name = function.__name__
        self.function = function

    def __call__(self, *args, **kwargs):
        self.function(self)

class Test:

    def __init__(self):
        pass

    # @property
    @property_name
    def temperature(self):
        print(self.property_name)
        return 24.5

    # @property
    @property_name
    def time(self):
        print(self.property_name)
        return "12:45 am"

if __name__ == '__main__':
    t = Test()
    print(t.temperature)
    print(t.time)

Now, so far I know, the property decorator doesn't has a way to get the name of the property as a string like temperature or time .

So, I decided to try to get the function name by writing the decorator property_name . Decorating the function with this decorator does exactly what I need. The decorator adds the attribute property_name to the class with the name of the function which has been called. So far everything works and is clear.

But, when I chain the property decorator, then I get troubles:

Traceback (most recent call last):
  File "test_func_name.py", line 28, in <module>
    t.temperature()
TypeError: 'NoneType' object is not callable

Debugging the code, I see that both methods temperature and time are None .

How can I chain my decorator to property ? Is there a better solution for that problem?

You have to return the value of the function you are calling in property_name.__call__ :

class property_name(object):
    def __init__(self, function):
        self.property_name = function.__name__
        self.function = function

    def __call__(self, *args, **kwargs):
        return self.function(self)

Then

$ python3 tmp.py
temperature
24.5
time
12:45 am

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