038类和对象:继承

父类:被继承的类
子类:继承的类

>>> class parent:
	def hello(self):
		print("正在调用父类的方法")

		
>>> class child(parent):
	pass

>>> p = parent()
>>> p.hello()
正在调用父类的方法
>>> c = child()
>>> c.hello()
正在调用父类的方法
import random as r  #先引用random

class Fish:          #定义一个父类Fish
    def __init__(self):#定义一个子类self
        self.x = r.randint(0,10)
        self.y = r.randint(0,10)

    def move(self):
        self.x -= 1
        print("我的位置是:",self.x,self.y)

class Goldfish(Fish):
    pass

class Crap(Fish):
    pass

class Salmon(Fish):
    pass

class Shark(Fish):    #虽然继承了Fish,但是后面重新定义就覆盖了
    def _init_(self):
        Fish.__init__(self)  #所以要引用上一个子类
        self.hungry = True

    def eat(self):
        if self.hungry:
            print("吃货的梦想就是天天有的吃")
            self.hungry = False
        else:
            print("太撑了,吃不下了")

使用super函数后

import random as r  #先引用random

class Fish:          #定义一个父类Fish
    def __init__(self):#定义一个子类self
        self.x = r.randint(0,10)
        self.y = r.randint(0,10)

    def move(self):
        self.x -= 1
        print("我的位置是:",self.x,self.y)

class Goldfish(Fish):
    pass

class Crap(Fish):
    pass

class Salmon(Fish):
    pass

class Shark(Fish):    #虽然继承了Fish,但是后面重新定义就覆盖了
    def _init_(self):
        super().__init__()  #使用super函数引用
        self.hungry = True

    def eat(self):
        if self.hungry:
            print("吃货的梦想就是天天有的吃")
            self.hungry = False
        else:
            print("太撑了,吃不下了")


>>> shark = Shark()
>>> shark.move()
我的位置是: 3 1


多重继承(尽量避免使用,会产生不可预见的bug)

>>> c = c()
>>> c.fool()
我是base1
>>> class base1:
	def foo1(self):
		print("我是base1")

		
>>> class base2:
	def foo2(self):
		print("我是base2")

		
>>> class c(base1,base2):
	pass
>>> c = c()
>>> c.foo1()
我是base1
>>> c.foo2()
我是base2
发布了42 篇原创文章 · 获赞 0 · 访问量 275

猜你喜欢

转载自blog.csdn.net/qq_43169516/article/details/103860359