双下划线
避免子类覆盖父类的方法:
class A(object):
def __method(self):
print("I'm a method in class A")
def method_x(self):
print("I'm another method in class A\n")
def method(self):
self.__method()
self.method_x()
class B(A):
def __method(self):
print("I'm a method in class B")
def method_x(self):
print("I'm another method in class B\n")
if __name__ == '__main__':
print("situation 1:")
a = A()
a.method()
b = B()
b.method()
print("situation 2:")
# a.__method()
a._A__method()
结果:
situation 1:
I'm a method in class A
I'm another method in class A
I'm a method in class A
I'm another method in class B
situation 2:
I'm a method in class A
首尾双下划线
python内部调用,可以在自己的类中覆写操作符:
class CrazyNumber(object):
def __init__(self, n):
self.n = n
def __add__(self, other):
return self.n - other
def __sub__(self, other):
return self.n + other
def __str__(self):
return str(self.n)
num = CrazyNumber(10)
print(num) # output is: 10
print(num + 5) # output is: 5
print(num - 20) # output is: 30