Python-100-Days/Day01-15/code/Day09/dependency.py

82 lines
1.9 KiB
Python
Raw Normal View History

2018-04-27 00:00:22 +08:00
"""
对象之间的依赖关系和运算符重载
Version: 0.1
Author: 骆昊
Date: 2018-03-12
"""
class Car(object):
2019-05-03 21:17:36 +08:00
def __init__(self, brand, max_speed):
self._brand = brand
self._max_speed = max_speed
self._current_speed = 0
2018-04-27 00:00:22 +08:00
2019-05-03 21:17:36 +08:00
@property
def brand(self):
return self._brand
2018-04-27 00:00:22 +08:00
2019-05-03 21:17:36 +08:00
def accelerate(self, delta):
self._current_speed += delta
if self._current_speed > self._max_speed:
self._current_speed = self._max_speed
2018-04-27 00:00:22 +08:00
2019-05-03 21:17:36 +08:00
def brake(self):
self._current_speed = 0
2018-04-27 00:00:22 +08:00
2019-05-03 21:17:36 +08:00
def __str__(self):
return '%s当前时速%d' % (self._brand, self._current_speed)
2018-04-27 00:00:22 +08:00
class Student(object):
2019-05-03 21:17:36 +08:00
def __init__(self, name, age):
self._name = name
self._age = age
2018-04-27 00:00:22 +08:00
2019-05-03 21:17:36 +08:00
@property
def name(self):
return self._name
2018-04-27 00:00:22 +08:00
2019-05-03 21:17:36 +08:00
# 学生和车之间存在依赖关系 - 学生使用了汽车
def drive(self, car):
print('%s驾驶着%s欢快的行驶在去西天的路上' % (self._name, car._brand))
car.accelerate(30)
print(car)
car.accelerate(50)
print(car)
car.accelerate(50)
print(car)
2018-04-27 00:00:22 +08:00
2019-05-03 21:17:36 +08:00
def study(self, course_name):
print('%s正在学习%s.' % (self._name, course_name))
2018-04-27 00:00:22 +08:00
2019-05-03 21:17:36 +08:00
def watch_av(self):
if self._age < 18:
print('%s只能观看《熊出没》.' % self._name)
else:
print('%s正在观看岛国爱情动作片.' % self._name)
2018-04-27 00:00:22 +08:00
2019-05-03 21:17:36 +08:00
# 重载大于(>)运算符
def __gt__(self, other):
return self._age > other._age
2018-04-27 00:00:22 +08:00
2019-05-03 21:17:36 +08:00
# 重载小于(<)运算符
def __lt__(self, other):
return self._age < other._age
2018-04-27 00:00:22 +08:00
if __name__ == '__main__':
2019-05-03 21:17:36 +08:00
stu1 = Student('骆昊', 38)
stu1.study('Python程序设计')
stu1.watch_av()
stu2 = Student('王大锤', 15)
stu2.study('思想品德')
stu2.watch_av()
car = Car('QQ', 120)
stu2.drive(car)
print(stu1 > stu2)
print(stu1 < stu2)