Underscore Meaning of Python Property Variable

Asked 2 years ago, Updated 2 years ago, 16 views

I have a question about Python's property.
Common codes have an underscore in front of the instance variable as shown below, but
What does this mean?
Is it necessary to use property?

class MyClass:

    def__init__(self, x):
        self._x = x

    @property
    defx(self):
        return self._x

    @x.setter
    def x (self, x):
        self._x = x
        do_something()

python

2022-09-30 16:37

2 Answers

If the name begins with an underscore, the instance variable is traditionally treated as a private variable.However, it is not a real private variable, so you can access it from the outside.

9. Class—Python 3.6.1 Document

In the case of the mentioned code, the getter and setter are defined so that they can be accessed by name x instead of _x.However, there should be no need for an underscore.

2.Embedded Functions—Python 3.6.1 Document


2022-09-30 16:37

The first underscore of a name is a customary naming to mean that "this variable is not exposed outside the class."

For example, PEP8 says:

_single_leading_underscore:week "internal use" indicator.E.g.from Import* does not import objects where name starts with underscore.

The following posts are also helpful: "What is the meeting of a single-and a double-undercore before an object name?" --Stack Overflow


2022-09-30 16:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.