继承->重写
class A(object):
def __init__(self):
print("super(B,self).__init__():运行A:init")
self.name = "cui" # # 父类的self变量同样存储到self中,在子类中使用self调用没一点问题
def C(self):
print("super(B, self).C():运行A:C,并调用D方法")
self.D()
def D(self):
print("A:D")
class B(A): # B继承了A
def __init__(self):
print("运行B:init")
super(B,self).__init__() # super().父类方法,可以直接应用父类方法
super(B, self).C()
self.age = 12
def D(self): # 通过继承实现方法重写, 这样不管是子类还是父类,只要调用D方法,那么只调用子类的方法,除非使用super().D()
print("D方法在子类B中被重写,所以A:C调用的是B:D")
print("B:D")
b = B()
# 运行结果如下
-----------------------
D:\install\python\python.exe D:/realsense_code/data_process/ex_rgb/dsfsd.py
运行B:init
super(B,self).__init__():运行A:init
super(B, self).C():运行A:C,并调用D方法
D方法在子类B中被重写,所以A:C调用的是B:D
B:D
-----------------------
多继承
== A1.init(self) 多继承的初始化方法,并且父类的self属性会放在self中==
如果多个父类中有相同名字的self变量则看为一个
class A1(object):
def __init__(self):
print("super(B,self).__init__():运行A:init")
self.name = "A1" # # 父类的self变量同样存储到self中,在子类中使用self调用没一点问题
def C1(self):
print("super(B, self).C():运行A:C,并调用D方法")
self.D()
def D1(self):
print("A:D")
class A2(object):
def __init__(self):
print("super(B,self).__init__():运行A:init")
self.name = "A2" # # 父类的self变量同样存储到self中,在子类中使用self调用没一点问题
def C2(self):
print("super(B, self).C():运行A:C,并调用D方法")
self.D()
def D2(self):
print("A:D")
class B(A1, A2): # B继承了A
def __init__(self):
print("运行B:init")
A1.__init__(self) # 多继承的初始化方法,并且父类的self属性会放在self中
A2.__init__(self) # 如果多个父类中有相同名字的self变量则看为一个
self.age = 12
def D(self): # 通过继承实现方法重写, 这样不管是子类还是父类,只要调用D方法,那么只调用子类的方法,除非使用super().D()
print("D方法在子类B中被重写,所以A:C调用的是B:D")
print("B:D")
b = B()
除此之外,父类和子类的变量可以通过self相互调用
装饰器
简单地说:他们是修改其他函数的功能的函数。装饰器的运行顺序,就是按照函数顺序执行就可以。至于用@ 符号,是用更短的符号实现函数分装。
@a_new_decorator == a_new_decorator(a_function_requiring_decoration)。
def a_new_decorator(a_func):
def wrapTheFunction():
print("I am doing some boring work before executing a_func()")
a_func()
print("I am doing some boring work after executing a_func()")
return wrapTheFunction
def a_function_requiring_decoration():
print("I am the function which needs some decoration to remove my foul smell")
a_function_requiring_decoration()
# outputs: "I am the function which needs some decoration to remove my foul smell"
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
# now a_function_requiring_decoration is wrapped by wrapTheFunction()
a_function_requiring_decoration()
# outputs:I am doing some boring work before executing a_func()
# I am the function which needs some decoration to remove my foul smell
# I am doing some boring work after executing a_func()