環境: Python 3.10.4
先放總結
在實際開發過程中,強烈不推薦調用_
或__
開頭的內容,像__str__
之類除外。
class Hello:
def __init__(self, one, two):
self._one = one
self.__two = two
h = Hello(1, 2)
print(h._one)
print(h.__two)
Output
1
Traceback (most recent call last):
File "/Users/yimt/Code/PycharmProjects/hello-python/hello.py", line 9, in <module>
print(h.__two)
AttributeError: 'Hello' object has no attribute '__two'
class Hello:
def _one(self):
print('one')
def __two(self):
print('two')
h = Hello()
h._one()
h.__two()
Output
Traceback (most recent call last):
File "/Users/yimt/Code/PycharmProjects/hello-python/learn.py", line 1, in <module>
import hello
File "/Users/yimt/Code/PycharmProjects/hello-python/hello.py", line 11, in <module>
h.__two()
AttributeError: 'Hello' object has no attribute '__two'
one
程序正常執行
hello.py
def _one():
print('one')
def __two():
print('two')
main.py
import hello
hello._one()
hello.__two()
Output
one
two