如何使用类和对象
知识点:
1、函数继承和调用
函数就是对象的动作
继承是指子类中的对象可以使用父类的函数属性,调用需self.函数名(见Go_Eat(self)函数)
class Animals: def breathe(self): print("breathing") def move(self): print("moving") def eat_food(self): print("eating food") class Mammals(Animals): def feed_young_with_milk(self): print("feeding young") class Giraffes(Mammals): def eat_leaves_from_trees(self): print("eating leaves") def Go_Eat(self): self.move() self.eat_food() reginald = Giraffes() reginald.Go_Eat()
moving eating food
2、初始化对象
当我们创建对象时,有时我们会设置一些值以便将来使用(这些值也称之为“属性”)。例如,当我们想在创建长颈鹿对象时设置一个在它身上斑点的数量,这件事要在初始化时做。
class Giraffes: def __init__(self,spots): self.giraffe_spots = spots
#我们把参数spots设置给self函数的一个叫giraffe_spots的对象变量(也就是它的属性) ozwald = Giraffes(100) print(ozwald.giraffe_spots)
100__init__ 前后都是两个下划线
课后练习:
1、长颈鹿乱舞
class Giraffes(): def Left_Foot_Forward(self): print("left foot forward") def Left_Foot_Backward(self): print("left foot back") def Right_Foot_Forward(self): print("right foot forward") def Right_Foot_Backward(self): print("right foot back") def dance(self): self.Left_Foot_Forward() self.Left_Foot_Backward() self.Right_Foot_Forward() self.Right_Foot_Backward() self.Left_Foot_Backward() self.Right_Foot_Backward() self.Right_Foot_Forward() self.Left_Foot_Forward() reginald = Giraffes() reginald.dance()
left foot forward left foot back right foot forward right foot back left foot back right foot back right foot forward left foot forward
import turtle t1 = turtle.Pen() t2 = turtle.Pen() t3 = turtle.Pen() t4 = turtle.Pen() t1.forward(50) t1.left(90) t1.forward(20) t1.right(90) t1.forward(20) t2.forward(40) t2.left(90) t2.forward(30) t2.right(90) t2.forward(30) t3.forward(50) t3.right(90) t3.forward(20) t3.left(90) t3.forward(20) t4.forward(40) t4.right(90) t4.forward(30) t4.left(90) t4.forward(30)
之前理解的有误:
t = turtle.Pen()
这应该是创建画笔,不是创建画布,一个画布中可以创建多个画笔,如图所示