Summarize Python's @property decorator

Major premise

class Man1():
    def __init__(self, name):
        self.name = name

With this definition, both the instance variable name can be referenced and rewritten.

#Initialization
Paul = Man("Paul")

#Can be referenced
print(Paul.name)
#Rewritable
Paul.name = Mac

I want to realize a private variable-like

But some instance variables

In some cases. in this case,

#Prefix the instagram variable__Defined in(This__name is mangled and this name cannot be referenced)
class Man():
    def __init__(self, name):
        self.__name = name

    #This function name should not overlap with an existing instance variable name
    @property
    def name(self):
        return self.__name

    #Need to define getter with the same name before setter
    #Without this setter the name property would be read-only
    @name.setter
    def name(self, name):
        self.__name = name

By

#Initialization
Paul = Man("Paul")

#reference
# Paul.name()is not
print(Paul.name)

#Rewrite
# Paul.name("Mac")is not
Paul.name = "Mac"

#No direct access to the original property(error)
Paul.__name
Paul.__name = "Mac"

However, it is possible to refer to and rewrite the instance variable __name with Paul._Man__name (so mock).

Recommended Posts

Summarize Python's @property decorator
Use a Property Decorator?
[Revised] property decorator that caches values
Decorator 1
Decorator 2
Decorator
Decorator