Treat Python in-class variables as private variables

In the following programs, the variable test in the class can be operated from the outside, which may cause a bug.

class MyClass(object):

    def __init__(self):
        self.test = 'test'


t = MyClass()
print(t.test)

#Can be edited directly
t.test = 'test2'
print(t.test)
test
test2

~~ You can make it impossible to edit from the outside by adding a double underscore to the variable in the function. ~~ Even with a double underscore, it seems that you can edit it in the following form without using a setter.

class MyClass(object):

    def __init__(self):
        self.__test = 'test'

    @property
    def test(self):
          return self.__test


t = MyClass()
print(t.test)

#Edit without using setter
t._MyClass__test = 'test2'
print(t._MyClass__test)

#Cannot be edited normally
t.__test = 'test3'
print(t.test)
test
test2
test2

pep8 also says "Generally, double leading underscores should be used only to avoid name conflicts with attributes in classes designed to be subclassed.", And adding double underscores to make variables look private It doesn't seem to be recommended. If you want to make it a private variable, the correct way is to add a single underscore at the beginning to indicate that it is a private variable.

class MyClass(object):

    def __init__(self):
        self._test = 'test'
        
    @property
    def test(self):
        return self._test
    
    @test.setter
    def test(self, value):
        self._test = value


t = MyClass()
print(t.test)

#Edit using setter
t.test = 'test2'
print(t.test)
test
test2

It should be noted that you can actually edit and operate without using setter.

class MyClass(object):

    def __init__(self):
        self._test = 'test'
        
    @property
    def test(self):
        return self._test
    
    @test.setter
    def test(self, value):
        self._test = value


t = MyClass()
print(t.test)

#Edit using setter
t.test = 'test2'
print(t.test)

#Edit without using setter
t._test = 'test3'
print(t._test)

Recommended Posts

Treat Python in-class variables as private variables
[Python] Variables
python memo: Treat lists as a set type
[Python] Get environment variables
(Python) Treat integer values as a set of flags
Private Python learning procedure
Python: Class and instance variables
About Python variables and objects
Python notes using perl-special variables
Handle environment variables in Python
# 1 [python3] Simple calculation using variables
Python class variables and instance variables
Python Beginner's Guide (Variables / Arrays)
Python variables and object IDs
python: Use the variables defined in the string format as they are