CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
jackfrued

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: jackfrued/Python-100-Days
Path: blob/master/Day01-15/code/Day09/dependency.py
Views: 729
1
"""
2
对象之间的依赖关系和运算符重载
3
4
Version: 0.1
5
Author: 骆昊
6
Date: 2018-03-12
7
"""
8
9
10
class Car(object):
11
12
def __init__(self, brand, max_speed):
13
self._brand = brand
14
self._max_speed = max_speed
15
self._current_speed = 0
16
17
@property
18
def brand(self):
19
return self._brand
20
21
def accelerate(self, delta):
22
self._current_speed += delta
23
if self._current_speed > self._max_speed:
24
self._current_speed = self._max_speed
25
26
def brake(self):
27
self._current_speed = 0
28
29
def __str__(self):
30
return '%s当前时速%d' % (self._brand, self._current_speed)
31
32
33
class Student(object):
34
35
def __init__(self, name, age):
36
self._name = name
37
self._age = age
38
39
@property
40
def name(self):
41
return self._name
42
43
# 学生和车之间存在依赖关系 - 学生使用了汽车
44
def drive(self, car):
45
print('%s驾驶着%s欢快的行驶在去西天的路上' % (self._name, car._brand))
46
car.accelerate(30)
47
print(car)
48
car.accelerate(50)
49
print(car)
50
car.accelerate(50)
51
print(car)
52
53
def study(self, course_name):
54
print('%s正在学习%s.' % (self._name, course_name))
55
56
def watch_av(self):
57
if self._age < 18:
58
print('%s只能观看《熊出没》.' % self._name)
59
else:
60
print('%s正在观看岛国爱情动作片.' % self._name)
61
62
# 重载大于(>)运算符
63
def __gt__(self, other):
64
return self._age > other._age
65
66
# 重载小于(<)运算符
67
def __lt__(self, other):
68
return self._age < other._age
69
70
71
if __name__ == '__main__':
72
stu1 = Student('骆昊', 38)
73
stu1.study('Python程序设计')
74
stu1.watch_av()
75
stu2 = Student('王大锤', 15)
76
stu2.study('思想品德')
77
stu2.watch_av()
78
car = Car('QQ', 120)
79
stu2.drive(car)
80
print(stu1 > stu2)
81
print(stu1 < stu2)
82
83