“_”的作用
在类A中定义了一个_method方法,按照约定是不能在类外面直接调用它的,为了可以在外面使用_method方法,又定义了method方法,method方法调用_method方法。
class A: def __method(self): print('This is a method from class A') def method(self): return self.__method()class B(A): def __method(self): print('This is a method from calss B')a=A()a.method()b=B()b.method()
- 私有属性或方法, 该方法或属性不应该在外部去调用(不建议在类的外面直接调用这个方法,但是也可以通过模块内方法调用)
"__"的作用
import inspectclass Person: # method1方法在类的外部可以访问 def method1(self): print("method1") # __method2方法在类的外部不可访问 def __method2(self): print("method2") def getmet2(self): return self.__method2()p = Person()p.method1()p._Person__method2() p.getmet2()methods = inspect.getmembers(p, predicate=inspect.ismethod)print(methods)
- Python中的name mangling(名称重整)技术 使__method变成了 _A__method 从而避免了A的子类覆盖其内容。
- 在python的类中,没有真正的私有化,不管是方法还是属性,为了编程的需要,约定加了下划线 _ 的属性和方法不属于API,不应该在类的外面访问,也不会被from M import * 导入。