类、对象和面向对象的编程
类:一堆函数的集合,是可以实例化出对象的模具,是具有共性的一类事物的统一描述
实例化: 对象 = 类() t = turtle.Pen()
对象:是类实例化出的实体,对象实实在在存在,完成具体工作
面向对象:程序员反复修改优化类,类实例化出对象,对象调用类里的函数来执行具体的操作哺乳动物类是动物类的子类,是在动物的基础上多了喂奶的功能。
猫是哺乳动物的子类,在哺乳动物的基础上多了捉老鼠的功能
类具有继承关系,子类将具有自身和父类的功能
6、类的定义:
class 类名(父类名):
pass
class Animals:
pass
class Mammals(Animals):
pass
class Cats(Mammals):
pass
class Animals(): def breathe(self): print('breathing') def move(self): print('moving') def eat(self): print('eating food') class Mammals(Animals): def breastfeed(self): print('feeding young') class Cats(Mammals): def __init__(self, spots): self.spots = spots def catch_mouse(self): print('catch mouse') def left_foot_forward(self): print('left foot forward') def left_foot_backward(self): print('left foot backward') def dance(self): self.left_foot_forward() self.left_foot_backward() self.left_foot_forward() self.left_foot_backward() kitty = Cats(10) print(kitty.spots) kitty.dance() kitty.breastfeed() kitty.move()
运行结果:
python的类、对象和面向对象的编程
猜你喜欢
转载自blog.csdn.net/hxxjxw/article/details/100087387
今日推荐
周排行