1.self的用法
2. 继承
子类继承父类,自动拥有父类的全部方法
>>> class Animal:
def run(self):
print('Animal is running !')
>>> class Dog(Animal):
pass
>>> class Cat(Animal):
pass
>>> dog = Dog()
>>> dog.run()
Animal is running !
>>> cat = Cat()
>>> cat.run()
Animal is running !
子类和父类拥有相同名称的函数,覆盖父类函数
>>> class Dog(Animal):
def run(self):
print('Dog is running')
>>> class Cat(Animal):
def run(self):
print('Cat is running')
>>> dog = Dog()
>>> dog.run()
Dog is running
>>> cat = Cat()
>>> cat.run()
Cat is running
3.组合
class Turtle:
def __init__(self,x):
self.num = x
class Fish:
def __init__(self,x):
self.num = x
class Pool:
def __init__(self,x,y):
self.turtle = Turtle(x)
self.fish = Fish(y)
def print_num(self):
print("水池里总共有乌龟%d只,小鱼%d只" % (self.turtle.num,self.fish.num))
>>> pool = Pool(15,20)
>>> pool.print_num()
水池里总共有乌龟15只,小鱼20只
4.相关的BIF
一个没有感情的笔记搬运工