mogumanman

【python】详解类class的继承、__init__初始化、super方法(五)

 

Python中类相关的一些基本点已经比较完整清晰了,本文继续深入Python中类的继承和_ _slots _ _属性

1、继承

  • 在Python中,同时支持单继承与多继承,一般语法如下:
class SubClassName(ParentClass1 [, ParentClass2, ...]):
    class_suite

  • 实现继承之后,子类将继承父类的属性,也可以使用内建函数insubclass()来判断一个类是不是另一个类的子孙类:
class Parent(object):
\'\'\'
parent class
\'\'\'
numList = []
def numdiff(self, a, b):
return a-b

class Child(Parent):
pass


c = Child()
# subclass will inherit attributes from parent class
#子类继承父类的属性
Child.numList.extend(range(10))
print(Child.numList)

print("77 - 2 =", c.numdiff(77, 2))

# built-in function issubclass()
print(issubclass(Child, Parent))
print(issubclass(Child, object))

# __bases__ can show all the parent classes
#bases属性查看父类
print(\'the bases are:\',Child.__bases__)

# doc string will not be inherited
#doc属性不会被继承
print(Parent.__doc__)
print(Child.__doc__)

代码的输出为:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
77 - 2 = 75
True
True
the bases are: (<class \'__main__.Parent\'>,)

    parent class

None

例子中唯一特别的地方是文档字符串。文档字符串对于类,函数/方法,以及模块来说是唯一的,也就是说doc属性是不能从父类中继承来的。


2、继承中的_ _init_ _
当在Python中出现继承的情况时,一定要注意初始化函数_init_的行为:

如果子类没有定义自己的初始化函数,父类的初始化函数会被默认调用;但是如果要实例化子类的对象,则只能传入父类的初始化函数对应的参数,否则会出错。
如果子类定义了自己的初始化函数,而在子类中没有显示调用父类的初始化函数,则父类的属性不会被初始化
如果子类定义了自己的初始化函数,在子类中显示调用父类,子类和父类的属性都会被初始化

2.1、子类没有定义自己的初始化函数,父类的初始化函数会被默认调用:

 

 如果不传入父类的参数name:

 

 

 2.2、子类定义了自己的初始化函数,而在子类中没有显示调用父类的初始化函数,则父类的属性不会被初始化

 

 

 

 在子类中没有显示调用父类的初始化函数,则父类的属性不会被初始化,因而此时调用子类中name属性不存在: 
AttributeError: ‘Child’ object has no attribute ‘name’

 

2.3、如果子类定义了自己的初始化函数,显示调用父类,子类和父类的属性都会被初始化

 

class Parent(object):
def __init__(self, name):
self.name = name
print("create an instance of:", self.__class__.__name__)
print("name attribute is:", self.name)

class Child(Parent):
def __init__(self):
#print("call __init__ from Child class")
super(Child,self).__init__(\'Tom\') #要将子类Child和self传递进去
#c = Child("init Child")
d = Parent(\'tom\')
c = Child()

 输出:

(\'create an instance of:\', \'Parent\')
(\'name attribute is:\', \'tom\')
(\'create an instance of:\', \'Child\')
(\'name attribute is:\', \'Tom\')

 

3、super的使用详解

  • super主要来调用父类方法来显示调用父类,在子类中,一般会定义与父类相同的属性(数据属性,方法),从而来实现子类特有的行为。也就是说,子类会继承父类的所有的属性和方法,子类也可以覆盖父类同名的属性和方法。

 

class Parent(object):
Value = "Hi, Parent value"
def fun(self):
print("This is from Parent")
#定义子类,继承父类
class Child(Parent):
Value = "Hi, Child value"
def ffun(self):
print("This is from Child")

c = Child()
c.fun()
c.ffun()
print(Child.Value)

输出结果:

This is from Parent
This is from Child
Hi, Child value

 

但是,有时候可能需要在子类中访问父类的一些属性,可以通过父类名直接访问父类的属性,当调用父类的方法是,需要将”self”显示的传递进去的方式:

class Parent(object):
Value = "Hi, Parent value"
def fun(self):
print("This is from Parent")

class Child(Parent):
Value = "Hi, Child value"
def fun(self):
print("This is from Child")
Parent.fun(self) #调用父类Parent的fun函数方法

c = Child()
c.fun()

输出: 

This is from Child
This is from Parent #实例化子类Child的fun函数时,首先会打印上条的语句,再次调用父类的fun函数方法

 这种方式有一个不好的地方就是,需要经父类名硬编码到子类中,为了解决这个问题,可以使用Python中的super关键字:

class Parent(object):
Value = "Hi, Parent value"
def fun(self):
print("This is from Parent")

class Child(Parent):
Value = "Hi, Child value"
def fun(self):
print("This is from Child")
#Parent.fun(self)
super(Child,self).fun()
#相当于用super的方法与上一调用父类的语句置换,super先找到Child子类对应的父类Parent,相当于做Parent.fun()执行了父类中的方法


c = Child()
c.fun()

This is from Child

This is from Parent #实例化子类Child的fun函数时,首先会打印上条的语句,再次调用父类的fun函数方法

 


#python 3.6版本中super().父类的方法
#Python 2.7版本中super(子类,self).父类方法,父类类名称后Fish(object)
import random as r
class Fish:
def __init__(self):
self.x = r.randint(0,100)
self.y = r.randint(50,100)
def move(self):
self.x += 1
print(\'wizhi:\',self.x,self.y)
class Goldfish(Fish):
pass
class Carp(Fish):
pass
class Salmon(Fish):
pass
class Shark(Fish):
def __init__(self):
super().__init__()
self.hungry = True

def eat(self):
if self.hungry:
print("好饿要吃东西!")
self.hungry = False
else:
print(\'吃多了,要运动\')

p = Fish()
p.move()

Car =Carp()
Car.move()

s = Shark()
s.move()
s.eat()
s.eat()

import random as r
class Fish(object):
def __init__(self):
self.hungry = True
self.x = r.randint(0,100)
self.y = r.randint(50,100)
def move(self):
self.x += 1
print(\'wizhi:\',self.x,self.y)
class Goldfish(Fish):
pass
class Carp(Fish):
pass
class Salmon(Fish):
pass
class Shark(Fish):

def __init__(self):
self.hungry = True
super(Shark,self).__init__()
def eat(self):
if self.hungry:
print("饱了")
self.hungry = False
else:
print(\'撑了,快跑!\')

f = Shark()
f.eat()
f.eat()
f.move()
 

分类:

技术点:

相关文章:

  • 2021-10-17
  • 2021-09-07
  • 2021-10-17
  • 2021-09-14
  • 2021-11-17
  • 2021-10-17
  • 2021-05-14
猜你喜欢
  • 2021-10-17
  • 2021-10-17
  • 2021-10-17
  • 2021-12-02
  • 2021-11-04
  • 2021-10-17
  • 2021-08-28
相关资源
相似解决方案