0%

Python基础-- init和继承

Python基础– init和继承

python

举例参考: 定义父类Cat和子类SmaCat这两个类均有init方法,最代码的使用对象调用子类的没有的init属性,但是父类却包含的方法.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Cat:
def __init__(self):
self.type = "猫"


class SmaCat(Cat):
def __init__(self):
self.color = "yellow"
# 以下是继承父类的调用方法,没有父类的调用,最下面直接需要父类的init魔法方法,会出现报错
# Cat.__init__(self)
# super(SmaCat,self).__init__()
# super().__init__()


xiaohua = SmaCat()
print(xiaohua.type)

进一步改进,从而能够调用父类Catinit方法,从而达到能够子类能够调用父类的init方法

1
2
3
4
5
6
7
8
9
10
11
12
13
class Cat:
def __init__(self, type):
self.type = type


class SmaCat(Cat):
def __init__(self, type):
Cat.__init__(self, type)


xiaohua = SmaCat(" huahua ")
print(xiaohua.type)
print(xiaohua)