Python creates read-only properties by adding the @property decorator to the top of the method.
The @property decorator converts the method to a read-only property of the same name, which can be used in conjunction with the defined property and serves mainly to prevent the property from being modified.
class DataSet(object): @property def method_with_property(self): ## contains @property return "hi" def method_without_property(self): ## without @property return "hi" l = DataSet() print(l.method_with_property) # With @property, you can invoke a method as if it were a property, without adding (). print(l.method_without_property()) #unspecified@property , The normal form of calling a method must be used,That is, add()
By adding @property, this method becomes a propertyIf you add () after it, then it is called as a function, while it is not callable.
class DataSet(object): def method_without_property(self): ## without @property return "hi" l = DataSet() print(l.method_without_property) #unspecified@property , The normal form of calling a method must be used,That is, add()
Used in conjunction with a defined property, this prevents the property from being modified Since there is no way to set private properties when python does the definition of a property, you have to do it through the @property method.
This hides the name of the attribute so that users can't change it when they use it. (This is where once you add theread-only (computing))
class DataSet(object): def __init__(self): self._images = 1 self._labels = 2 # Define the name of the attribute @property def images(self): # After adding @property to a method, the method is equivalent to a property, which can be used by the user, and the user has no way to modify it. return self._images @property def labels(self): return self._labels l = DataSet() # When the user makes a property call, he or she can just call images without knowing the property name _images, so the user can't change the property, thus protecting the properties of the class. print() # added@propertyempress,Methods can be invoked in the form of calling properties,empress面不需要加()。
to this article on the use of @property in python on this article, more related python @property content please search my previous posts or continue to browse the following related articles I hope that you will support me in the future more!