Describe it as a memo.
Python has virtually no Private attribute, but you can define a function internally with _
module/func.py
def _func():
return something
module/__init__.py
from .module import func
In the above case
test.py
from module import *
print(func._func())
ImportError: cannot import name 'func' from 'module.func'
From M import * does not import functions that start with one underscore But,
module/func.py
class Net():
def _func(self):
return 'something'
module/__init__.py
from .module import Net
In the above case
test.py
from module import *
print(Net()._func())
Can be called.
That is, with __init__.py
in the call to ʻimport *`,
module/__init__.py
from .module import _variable
Because it cannot be described.
※important _Func () can be used unless it is described as import *
Of course, it also has the functions explained above and calls the name mangling mechanism. Originally, the name mangling mechanism This is for the purpose of avoiding name conflicts between the parent class and the child class.
module/func.py
class Net():
def __func(self):
return 'something'
module/__init__.py
from .module import Net
In the above case
test.py
from module import *
print(Net()._Net_func())
Instead of calling _Net_func (), you can create a pseudo private attribute
Become a magic method.
There are existing magic methods such as __init__
, __call__
, and __iter__
.
This allows you to write your class neatly.
Do not define a new one yourself in normal development.
Recommended Posts