类 对象 面向对象
类:物以类聚人以群分,是函数的集合,可实例化出对象的模具。
实例化:对象 = 类()
对象:是类实例化出的实体,对象实实在在存在,完成具体工作。
面向对象:程序员反复修改优化类,类实例化出对象,对象调用类里的函数执行具体操作。
动物 Animals ----- (breath,move,eat)
哺乳动物 Mammals -----(breastfeed)
猫 Cats ----- (catch_mouse)
上面的类是下面类的父类;下面类是上面类的子类;
子类实例化出来的对象,可以使用自身和父类的函数变量;
类的定义:
class 类名(父类名):
pass
class Animals:
pass
class Mammals(Animals):
pass
class Cats(Mammals):
pass
先用pass占位置,起架构;再用具体的函数替换pass完善类。
类里定义函数,语法规定第一个参数必须是self
_ init _函数,在新对象实例化时会自动运行,用于给新对象赋初值
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")
kitty = Cats(10)#实例化时运行__init__函数,给spots赋值,告知kitty有10个斑点
print(kitty.spots)
10
kitty.catch_mouse()
catch mouse
对象调用类里的函数,用对象.函数名;
对象调用类里的变量,用对象.变量名。
类内定义函数时,如调用自身或父类的函数与变量,须用self.引导,应写为self.函数名或self.变量名
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("forward")
def left_foot_backward(self):
print("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)
10
kitty.dance()
forward
backward
forward
backward
kitty.breastfeed()
feeding young
kitty.move()
moving