1. 总结环境: Python 3.10.4
先放总结
| 单下划线 | 双下划线 | |
|---|---|---|
| 类属性和方法 | True | False |
| 子类调用父类属性和方法 | True | False |
| 模块函数 | True | True |
在实际开发过程中,强烈不推荐调用_或__开头的内容,像__str__之类除外。
2. 类 2.1. 属性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, in2.2. 方法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, in3. 模块import hello File "/Users/yimt/Code/PycharmProjects/hello-python/hello.py", line 11, in 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



