I specified a double underscore for the function in the class and tried it as a Private attribute, but it was recorded when calling the function. <Addition (see pep8): In general, the method of adding two underscores at the beginning of the name is to avoid conflicting attributes of classes designed to be subclassed. Should only be used. >
class HogeHoge:
def __init__(self):
pass
def __FugaFuga(self):
iam = "king"
return iam
I want to print the return value "king" of __FugaFuga at this time,
iam = _HogeHoge__FugaFuga()
print(iam)
# iam = _HogeHoge__FugaFuga()
# NameError: name '_HogeHoge__FugaFuga' is not defined
If _HogeHoge__FugaFuga
is not found in NameError ...
HogeHoge = HogeHoge()
iam = HogeHoge.__FugaFuga()
# iam = HogeHoge.__FugaFuga()
# AttributeError: 'HogeHoge' object has no attribute '__FugaFuga'
Then, when the class and the function are separated, the function __FugaFuga
cannot be found ...
Success story:
class HogeHoge:
def __init__(self):
pass
def __FugaFuga(self):
iam = "common people"
return iam
HogeHoge = HogeHoge()
iam = HogeHoge._HogeHoge__FugaFuga()
print(iam)
Execution result:
C:\Users\***\test>python main.py
common people
It seems that the function of class HogeHoge
is _HogeHoge__FugaFuga
.
I referred to the article on the following site. Let's master Python underscore (_)! About python encapsulation and mangling PEP8: Python Code Style Guide
Recommended Posts