课时121
?
#通过继承使用方法
class A1:
def say_a1(self):
print("a1")
class B1(A1):
pass
b1=B1()
b1.say_a1()
#通过继承使用方法
class A2():
def say_a2(self):
print("a2")
class B2:
def __init__(self,a):
self.a=a
a2=A2()
b2=B2(a2) #b2有了a2这个对象,于是就可以调用a2的方法
b2.a.say_a2()
执行结果:
a1
a2
#测试has-a关系,使用组合
class Mobilefphone:
def __init__(self,cpu,screen):
self.cpu=cpu
self.screen=screen
class CPU:
def calculate(self):
print("caculation")
class Screen:
def display(self):
print("show")
a=Mobilefphone(CPU(),Screen())
a.cpu.calculate()
a.screen.display()
执行结果:
caculation
show
课时122
?
#测试工厂模式
class Car_factory:
def create_car(self,brand):
self.brand=brand
if brand=="奔驰":
return Benz()
elif brand=="宝马":
return BNF()
elif brand=="比亚迪":
return BYD()
else:
return "unknown"
class Benz:
pass
class BNF:
pass
class BYD:
pass
factory=Car_factory()
c1=factory.create_car("奔驰")
print(c1)
执行结果:
<__main__.Benz object at 0x000001EE9243A708>
课时123
?
#单例模式
class Mysinglton:
__obj=None #类属性
def __new__(cls, *args, **kwargs):
if cls.__obj==None:
cls.__obj=object.__new__(cls)
return cls.__obj
def __init__(self,name):
print("aa")
self.name=name
a1=Mysinglton("aa")
b1=Mysinglton("bb")
print(a1)
print(b1)
执行结果:
aa
aa
<__main__.Mysinglton object at 0x00000138FE506D48>
<__main__.Mysinglton object at 0x00000138FE506D48>
?
|