一.基本理解
class Animal(object): def __init__(self, age, color): self.bodyage = age self.bodycolor = color print(age, color) class Dog(Animal): def nicnamed(self, name, home, owner): print(f"Tis dog named {name}, and lives in {home}, his owner is {owner}") dog = Dog('15', 'white') dog.nicnamed('xiaodong', 'futian', 'Miki')
1.初始化函数:
基类Animal中有一个名为__init__的函数,__init__函数是初始化函数
2.初始化函数中的 属性 bodyage bodycolor【为类Animal的属性】:
bodyage 和 bodycolor只是属性,不是变量,不能直接被其他函数调用
self.bodyage = age # 将self的bodyage属性 设为 age
self.bodycolor = color # 将self的bodycolor属性 设为 color
如上,age和color才是变量,可以被函数调用
3.实例化:
按照类Dog(蓝图)创建一个空对象,并将这个对象赋值给dog。
如果,类Dog(蓝图)中有__init__(初始化函数),则会调用这个函数对新创建的空对象进行初始化(例如:给类中的属性赋值)
所以,实例化时,就需要将初始化函数需要的参数传入,即:
dog = Dog('15', 'white')
Dog('15', 'white')的入参个数 = 基类Animal的__init__函数的参数个数(除去self)
二.修改下代码,深入理解
1.将__init__修改为chushihua:
class Animal(object): def chushihua(self, age, color): self.bodyage = age self.bodycolor = color print(age, color) class Dog(Animal): def nicnamed(self, name, home, owner): print(f"Tis dog named {name}, and lives in {home}, his owner is {owner}") dog = Dog('15', 'white') dog.nicnamed('xiaodong', 'futian', 'Miki')
执行结果如下:
__init__是python默认的初始化函数,修改后,即为class Animal没有初始化函数,所以实例化时,创建空对象时不需要初始化,即Dog('15', 'white')多出了两个参数。
把参数去掉可以正常执行:如下
class Animal(object): def chushihua(self, age, color): self.bodyage = age self.bodycolor = color print(age, color) class Dog(Animal): def nicnamed(self, name, home, owner): print(f"Tis dog named {name}, and lives in {home}, his owner is {owner}") dog = Dog() dog.nicnamed('xiaodong', 'futian', 'Miki')
2.调用类Animal中chishihua函数【隐式继承】
此时,在没有__init__函数的基础上,想要获取到类Animal中函数chishihua的属性,则需要继续调用这个函数,
并且 属性 bodyage 和 bodycolor 已经成为函数chushihua的属性,而不是类Animal的属性,
所以需要作为函数的入参去调用chushihua函数
如下:
class Animal(object): def chushihua(self, age, color): self.bodyage = age self.bodycolor = color print(age, color) class Dog(Animal): def nicnamed(self, name, home, owner): print(f"Tis dog named {name}, and lives in {home}, his owner is {owner}") dog = Dog() dog.chushihua('15', 'white') dog.nicnamed('xiaodong', 'futian', 'Miki')