CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
Path: blob/master/Day01-15/code/Day09/dependency.py
Views: 729
"""1对象之间的依赖关系和运算符重载23Version: 0.14Author: 骆昊5Date: 2018-03-126"""789class Car(object):1011def __init__(self, brand, max_speed):12self._brand = brand13self._max_speed = max_speed14self._current_speed = 01516@property17def brand(self):18return self._brand1920def accelerate(self, delta):21self._current_speed += delta22if self._current_speed > self._max_speed:23self._current_speed = self._max_speed2425def brake(self):26self._current_speed = 02728def __str__(self):29return '%s当前时速%d' % (self._brand, self._current_speed)303132class Student(object):3334def __init__(self, name, age):35self._name = name36self._age = age3738@property39def name(self):40return self._name4142# 学生和车之间存在依赖关系 - 学生使用了汽车43def drive(self, car):44print('%s驾驶着%s欢快的行驶在去西天的路上' % (self._name, car._brand))45car.accelerate(30)46print(car)47car.accelerate(50)48print(car)49car.accelerate(50)50print(car)5152def study(self, course_name):53print('%s正在学习%s.' % (self._name, course_name))5455def watch_av(self):56if self._age < 18:57print('%s只能观看《熊出没》.' % self._name)58else:59print('%s正在观看岛国爱情动作片.' % self._name)6061# 重载大于(>)运算符62def __gt__(self, other):63return self._age > other._age6465# 重载小于(<)运算符66def __lt__(self, other):67return self._age < other._age686970if __name__ == '__main__':71stu1 = Student('骆昊', 38)72stu1.study('Python程序设计')73stu1.watch_av()74stu2 = Student('王大锤', 15)75stu2.study('思想品德')76stu2.watch_av()77car = Car('QQ', 120)78stu2.drive(car)79print(stu1 > stu2)80print(stu1 < stu2)818283