"""
依赖关系: 在局部变量,方法的形参,或者对静态方法的调用中实现.
可以简单地理解,依赖就是一个类A使用到了另一个类B,仅仅是“使用到”,类B本身并不属于类A,或者说类A并不拥有类B。依赖关系是偶然性的、临时性的,但是因为类B本身被类A引用到,所以B类的变化也会影响到类A。比较常见的场景就是人乘飞机从一地到另一地,飞机和人之间并没有所属关系,只是一种临时性的出行工具,此时人和飞机之间就是依赖关系。
依赖关系在代码上体现为三种形式:
1. 类B作为类A方法的形参
2. 类B作为类A方法的局部变量
3. 类A调用类B的静态方法
"""
# 依赖关系,上班需要依赖交通工具,可以是滴滴也可以是地铁,只要滴滴和地铁都实现了open_door()和close_door(方法)
class Go2Work(object):
def open_door(self, car):
print("等待车开门")
car.open_door() # 此处的car.open_door() 只要其他类实现了open_door()这个方法,就可以直接使用,这就是类的多态。
def get_on_the_car(self):
print("进入车厢")
def close_door(self, car):
print("等待车关门")
car.close_door()
def get_off_the_car(self):
print("下车")
def __ge__(self, other):
pass
def __lt__(self, other):
pass
def __le__(self, other):
pass
def __gt__(self, other):
pass
def __eq__(self, other):
pass
def __ne__(self, other):
pass
class DiDi(object):
def open_door(self):
print("滴滴 --> 打开了车门")
def close_door(self):
print("滴滴 --> 关闭了车门")
class Subway(object):
def open_door(self):
print("地铁 --> 打开了车门")
def close_door(self):
print("地铁 --> 关闭了车门")
work = Go2Work()
car = Subway()
work.open_door(car)
work.get_on_the_car()
work.close_door(car)
work.get_off_the_car()
# 类B作为类A方法的形参
class Person(object):
def flying(self, plane):
plane.fly()
class Plane(object):
def fly(self):
print ("The plane is flying.")
>>> person = Person()
>>> plane = Plane()
>>> person.flying(plane)
The plane is flying.
>>>
# 类B作为类A方法的局部变量
class Person(object):
def flying(self):
self.plane = Plane()
plane.fly()
class Plane(object):
def fly(self):
print ("The plane is flying")
>>> person = Person()
>>> person.flying()
The plane is flying.
>>>
# 类A调用类B的静态方法
class Person(object):
def flying(self):
Plane.fly()
class Plane(object):
@staticmethod
def fly():
print ("The plane is flying.")
>>> person = Person()
>>> person.flying()
The plane is flying.
>>>