Talking about property Before decorator , Let's start with an example :
class MyClass:
def __init__(self, word):
self._word = word
def word(self):
return self._word
my = MyClass('Hello')
print(my.word())
print(my.word)
Execute this code , Will output the following results :
Hello
<bound method MyClass.word of <__main__.MyClass object at 0x7fee500b61f0>>
The main function of this code is through word Method returns a string . And the last line goes straight to word Method . stay Python In language , Anything can be regarded as an object , The method is no exception . So it directly outputs word The object form of the method .
however my.word This form of invocation , It's also a way to access properties , So this code can also be seen as word Methods are used as properties , Instead of getting word Object itself . therefore , If you want to word Methods are used as properties , Then use property Decorator . Let's take a look at the improved code :
class MyClass:
def __init__(self, word):
self._word = word
# take word Methods become properties
@property
def word(self)