How does the @property decorator work in Python?

后端 未结 13 2068
闹比i
闹比i 2020-11-21 04:49

I would like to understand how the built-in function property works. What confuses me is that property can also be used as a decorator, but it only

13条回答
  •  [愿得一人]
    2020-11-21 05:50

    Here is a minimal example of how @property can be implemented:

    class Thing:
        def __init__(self, my_word):
            self._word = my_word 
        @property
        def word(self):
            return self._word
    
    >>> print( Thing('ok').word )
    'ok'
    

    Otherwise word remains a method instead of a property.

    class Thing:
        def __init__(self, my_word):
            self._word = my_word
        def word(self):
            return self._word
    
    >>> print( Thing('ok').word() )
    'ok'
    

提交回复
热议问题