环境: Python 3.10.4
1. 总结
先放总结
单下划线 | 双下划线 | |
---|---|---|
类属性和方法 | 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, in <module>
print(h.__two)
AttributeError: 'Hello' object has no attribute '__two'
2.2. 方法
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
3. 模块
程序正常执行
hello.py
def _one():
print('one')
def __two():
print('two')
main.py
import hello
hello._one()
hello.__two()
Output
one
two