面向对象编程
简单的来说,类就是蓝图和模板,对象就是类的实例,换言之,类是抽象,对象是具体的。在面向对象的编程世界中,一切都可以是对象(万物可对象),对象有自己的行为和属性,每个对象都是独特的,而且对象一定属于某个类。
当把一堆拥有共同特征的对象的静态特征(属性)和动态特征(行为) 抽取出来做成一个类
定义类
关键字:class
其中用函数来模拟对象的动态特征
创建和使用对象
例子,student = Student('Ana', 16)
访问可见性问题
在python中访问权限,只有两种方式
- 公开的
- 私有的
希望是私有的,在前面加上双下划线__。
注意:python中并没有从语法严格保证私有的私密性,只有更换个名字还是可以访问到他们,因为我们认为开放总是比封闭要好。
实际的开发中不建议把属性设置为私有(可能导致子类无法访问),因此,加上单下划线_表示该属性受到保护,别的类要是访问就要注意,但这种只是一种暗喻,并不是强制。
面对对象的支柱
三大支柱:封装,多态,继承
练习
- 定义一个类描述数字时钟
- 定义一个类计算两个已知点的距离
-
定义一个类描述平面上的点并提供移动点和计算到另一个点距离的方法
1.
#数字时钟的类
import time
class Clock():
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second
def run(self):
self.second += 1
if self.second > 59:
self.minute += 1
self.second %= 60
if self.minute > 59:
self.hour += 1
self.minute %= 60
if self.hour > 23:
self.hour %= 24
def show(self):
return '%02d:%02d:%02d' % (self.hour,self.minute,self.second)
def main():
clock1 = Clock(23,59,59)
while True:
print(clock1.show())
time.sleep(1)
clock1.run()
if __name__ == '__main__':
main()
2.
#已知两点计算距离
import math
class Point():
def __init__(self,x1,y1,x2,y2, distance):
self.x_1 = x1
self.x_2 = x2
self.y_1 = y1
self.y_2 = y2
self.distance = distance
def long(self):
self.distance = math.sqrt((self.x_2 - self.x_1)**2 +
(self.y_2 - self.y_1)**2)
return self.distance
def show(self):
print('(%d,%d) 和 (%d,%d)距离是%d' % (self.x_1,self.y_2,self.x_2,self.y_2, self.distance))
def main():
points = Point(0,0,3,4,0)
points.long()
points.show()
if __name__ == '__main__':
main()
3.
#定义一个类描述平面上的点并提供移动点和计算到另一个点距离的方法
from math import sqrt
class Point(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def move_to(self, x, y):
self.x = x
self.y = y
def move_by(self, dx, dy):
self.x += dx
self.y += dy
def distance_to(self, other):
dx = self.x - other.x
dy = self.y - other.y
return sqrt(dx**2 + dy**2)
def __str__(self):
return '(%s,%s)' % (str(self.x), str(self.y))
def main():
p1 = Point(3,5)
p2 = Point()
print(p1)
print(p2)
p2.move_by(-1,2)
print(p2)
print(p1.distance_to(p2))
if __name__ == '__main__':
main()