There are no “private” instance variables in Python that can only be accessed from within an object.

I checked it because there were a few things

python


# -*- coding: utf-8 -*-

class Hoge(object):

    def __init__(self):

        self.__foo = 'foo'
        self._bar = 'bar'


hoge = Hoge()

# AttributeError: 'Hoge' object has no attribute '__foo'
# print hoge.__foo

print hoge._bar
print hoge._Hoge__foo

print hoge.__dict__

Execution result

bar foo {'_Hoge__foo': 'foo', '_bar': 'bar'}

Somehow Hoge .__ foo is a private property. The property with two unscos will behave like a private because name mandaring is performed.

It seems that hiding variables is not the main purpose, so I'll put it in my head for the time being.

Keep in mind that the rules of difficulty are primarily to prevent accidents; it is still possible to access and modify variables that are considered private in a convincing way. is. This specification is even useful in special situations such as debuggers.

http://docs.python.jp/2/tutorial/classes.html#tut-private

Recommended Posts

There are no “private” instance variables in Python that can only be accessed from within an object.
Set up an FTP server that can be created and destroyed immediately (in Python)
A mechanism to call a Ruby method from Python that can be done in 200 lines
Scripts that can be used when using bottle in Python
Create an instance of a predefined class from a string in Python
[Python] It seems that global variables cannot be referenced in Multiprocessing
Python standard input summary that can be used in competition pro
There is no switch in python
[Python3] Code that can be used when you want to cut out an image in a specific size