What object is _(underlined) before the name?

Asked 2 years ago, Updated 2 years ago, 123 views

What's the difference between one underlined object name and two underlined object names? Why are you using it? Are functions and variables used in the same sense?

python private underscores double-underscore naming-convention

2022-09-22 11:11

1 Answers

_: Writing with _name in the class is This is to inform the programmer that attribute or method is private. When import *, object whose name starts with _ is not imported. There is no other function.

__(Name Mangling):

The identifier whose name starts with more than one underscore will be replaced with the _classname__spam. So it's usually used to define a class-private instance, a class variable, a method, a global variable, and so on.

However, it is important to note that this mangling only serves to prevent accidental access to private, It is still possible to access/modify private if you decide.

class foo():
    def __init__(self):
        self.__myPrivateInt = 3

    def printPrivate(self):
        print(self.__myPrivateInt)

myfoo = foo()
#printmyfoo.__myPrivateInt #DirectAccess -> Error

mydict = myfoo.__dict__
mydict['_foo__myPrivateInt'] = 4 #___myPrivateInt changed
myfoo.printPrivate()

Result: 4


2022-09-22 11:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.