最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

python类继承与子类实例初始化用法分析

来源:动视网 责编:小采 时间:2020-11-27 14:32:43
文档

python类继承与子类实例初始化用法分析

python类继承与子类实例初始化用法分析:本文实例讲述了python类继承与子类实例初始化用法。分享给大家供大家参考。具体分析如下: [ 先贴参考书籍原文(中文英文对照)] __init__方法介绍: If a base class has an __init__() method the derived class's __init__(
推荐度:
导读python类继承与子类实例初始化用法分析:本文实例讲述了python类继承与子类实例初始化用法。分享给大家供大家参考。具体分析如下: [ 先贴参考书籍原文(中文英文对照)] __init__方法介绍: If a base class has an __init__() method the derived class's __init__(


本文实例讲述了python类继承与子类实例初始化用法。分享给大家供大家参考。具体分析如下:

[ 先贴参考书籍原文(中文英文对照)]
__init__方法介绍:
If a base class has an __init__() method the derived class's __init__() method must explicitly call it to ensure proper initialization of the base class part of the instance; for example: "BaseClass.__init__(self, [args...])"
As a special contraint on constructors, no value may be returned; doing so will cause a TypeError to be raised at runtime.

如果其基类也具有__init__(), 必须显式地在__init__()调用它, 以保证能够适当地初始化它的基类部分;例如: "BaseClass.__init__(self, [args...])"作为构造器的特殊情况, 它没有值被返回, 如果返回某个值, 会在运行时抛出异常TypeError.

1.子类定义了__init__方法时若未显示调用基类__init__方法,python不会帮你调用,解释运行都Ok

class A():
 def __init__(self):
 print 'a'
class B(A):
 def __init__(self):
 print 'b'
if __name__=='__main__':
 b=B()
>>> 
b

2.子类未定义__init__方法时,python会自动帮你调用首个基类的__init__方法,注意是首个。即:子类继承自多个基类时,只有第一个基类的__init__方法会被调用到:

class A:
 def __init__(self):
 print 'a'
class B:
 def __init__(self):
 print 'b'
class C(B):
 def __init__(self):
 print 'c'
 pass
class D1(A,B,C):
 pass
class D2(B,A,C):
 pass
class D3(C,B,A):
 pass
if(__name__=='__main__'):
 print 'd1------->:'
 d1=D1()
 print 'd2------->:'
 d2=D2()
 print 'd3------->:'
 d3=D3()
>>> 
d1------->:
a
d2------->:
b
d3------->:
c

3)基类未定义__init__方法时,若此时子类显示调用基类__init__方法时,python向上超找基类的基类的__init__方法并调用,实质同2

class A:
 def __init__(self):
 print 'a'
class B:
 def __init__(self):
 print 'b'
class C1(B,A):
 pass
class C2(A,B):
 pass
class D1(C1):
 def __init__(self):
 C1.__init__(self)
class D2(C2):
 def __init__(self):
 C2.__init__(self)
if(__name__=='__main__'):
 print 'd1------->:'
 d1=D1()
 print 'd2------->:'
 d2=D2()
>>> 
d1------->:
b
d2------->:
a

希望本文所述对大家的Python程序设计有所帮助。

文档

python类继承与子类实例初始化用法分析

python类继承与子类实例初始化用法分析:本文实例讲述了python类继承与子类实例初始化用法。分享给大家供大家参考。具体分析如下: [ 先贴参考书籍原文(中文英文对照)] __init__方法介绍: If a base class has an __init__() method the derived class's __init__(
推荐度:
标签: 分析 python 类继承
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top