环境: 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
本文探讨了Python中单下划线和双下划线的使用,以及它们对类属性和方法的访问影响。通过示例展示了尝试访问__two等私有属性时会引发AttributeError。同时,解释了在实际开发中避免直接调用以_或__开头的非公开成员的推荐做法。此外,还展示了模块函数的正常调用过程。
1075

被折叠的 条评论
为什么被折叠?



