继承
#encoding:utf-8
class Animal:
def eat(self):
print("吃吃吃")
def drink(self):
print("喝喝喝")
def sleep(self):
print("睡觉")
def run(self):
print("跑")
class Dog(Animal):
def bark(self):
print("汪汪汪")
class Cat(Animal):
def catch(self):
print("捉老鼠")
wangcai = Dog()
wangcai.eat()
wangcai.bark()
mimi = Cat()
mimi.run()
mimi.catch()
运行结果:
吃吃吃
汪汪汪
跑
捉老鼠
可以多层继承,子类可以直接调用父类的父类的函数
class Animal:
def eat(self):
print("吃吃吃")
def drink(self):
print("喝喝喝")
def sleep(self):
print("睡觉")
def run(self):
print("跑")
class Dog(Animal):
def bark(self):
print("汪汪汪")
class xiaotq(Dog):
def fly(self):
print("-------飞-----")
xiaotq = xiaotq()
xiaotq.fly()
xiaotq.eat()
xiaotq.bark()
重写
#encoding:utf-8
class Animal:
def eat(self):
print("吃吃吃")
def drink(self):
print("喝喝喝")
def sleep(self):
print("睡觉")
def run(self):
print("跑")
class Dog(Animal):
def bark(self):
print("汪汪汪")
class xiaotq(Dog):
def fly(self):
print("-------飞-----")
#方法的重写,名字必须与父类一样
def bark(self):
print("++=狂叫+++")
xiaotq = xiaotq()
xiaotq.fly()
xiaotq.eat()
xiaotq.bark()
运行结果:
-------飞-----
吃吃吃
++=狂叫+++
调用被重写的方法:
#encoding:utf-8
class Animal:
def eat(self):
print("吃吃吃")
def drink(self):
print("喝喝喝")
def sleep(self):
print("睡觉")
def run(self):
print("跑")
class Dog(Animal):
def bark(self):
print("汪汪汪")
class xiaotq(Dog):
def fly(self):
print("-------飞-----")
def bark(self):
print("++++狂叫+++")
#调用被重写的父类的方法:
Dog.bark(self) #方法一
super().bark() #方法二
xiaotq = xiaotq()
xiaotq.fly()
xiaotq.eat()
xiaotq.bark()
多继承
python支持多继承
class Base(object):
def test(self):
print("======Base====")
class A(Base):
def test1(self):
print("test1--------")
class B(Base):
def test2(self):
print("test2=======")
class C(A,B):
pass
c = C()
c.test1()
c.test2()
c.test()
运行结果:
test1--------
test2=======
======Base====
class Base(object):
def test(self):
print("======Base====")
class A(Base):
def test(self):
print("test1--------")
class B(Base):
def test(self):
print("test2=======")
class C(A,B):
def test(self):
print("cccccccccc=======")
c = C()
c.test()
print(C.__mro__) #调用方法时的搜索顺序,如果在某个类中找到了方法,就停止搜索
运行结果:
cccccccccc=======
(<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class '__main__.Base'>, <class 'object'>)
所以,设计类时,要尽量避免出现相同的类名