码迷,mamicode.com
首页 > 编程语言 > 详细

python - 构造函数

时间:2017-08-03 21:51:51      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:python   构造函数   


1. 如果子类定义了自己的__init__构造方法函数,当子类的实例对象被创建时,子类只会执行自己的__init__方法函数,如果子类未定义自己的构造方法函数,会沿着搜索树找到父类的构造方法函数去执行父类里的构造方法函数。



2. 如子类定义了自己的构造方法函数,如果子类的构造方法函数内没有主动调用父类的构造方法函数,那父类的实例变量在子类不会在刚刚创建子类实例对象时出现了。


[root@leco day8]# cat t4.py 

#!/usr/bin/env python
class aa:  
        def __init__(self):  
                self.x = 10  
                self.y = 12  
        def hello(self, x):  
                return x + 1  
class bb(aa):  
        def __init__(self):                 
                aa.__init__(self)  
                self.z = 14  
          
          
a = aa()  
print a.x, a.y  
b = bb()  
print b.x, b.y

[root@leco day8]# python t4.py 

10 12

10 12

要是没有调用父类的构造函数结果报错

[root@leco day8]# cat t4.py 

#!/usr/bin/env python
class aa:  
        def __init__(self):  
                self.x = 10  
                self.y = 12  
        def hello(self, x):  
                return x + 1  
class bb(aa):  
        def __init__(self):                 
                #aa.__init__(self)  
                self.z = 14  
          
          
a = aa()  
print a.x, a.y  
b = bb()  
print b.x, b.y

 

[root@leco day8]# python t4.py 

10 12

Traceback (most recent call last):

  File "t4.py", line 18, in <module>

    print b.x, b.y  

AttributeError: bb instance has no attribute ‘x‘


python - 构造函数

标签:python   构造函数   

原文地址:http://caimengzhi.blog.51cto.com/9787265/1953423

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!