Python的Object基类的__init__方法

Python的Object基类的__init__方法


Python的__init__方法是用来初始化的实例的,是在__new__()方法执行后但是还没有return的情况下执行的__init__()方法。__new__()方法是用来创建实例的。这个__init__类似于构造方法,是可以直接从object类中继承的。如果一个BaseClass有__init__()方法,那么他的派生类(子类)需要显示的执行这个方法,不然是无法初始化BaseClass类的属性。__init__()方法是没有返回值的,并且如果有除了self意外的参数的话,在调用时是需要指定的

创建类:

class Mytest1:
    def __init__(self,value):
        self._value = value
        self._children = []
    
    def myprint(self):
        print('You point value : ',self._value)


if __name__ == '__main__':
    t = Mytest1(1)    
    t.myprint()


输出:

You point value :  1

如果此时在实例化Mytest1时没有将value这个参数指定值,那么就会报错:

Traceback (most recent call last):
  File "E:\workspace\mystudy\com\dgb\object\myinit.py", line 17, in <module>
    t = Mytest1()    
TypeError: __init__() missing 1 required positional argument: 'value'

在父类和子类的环境中:

class Mytest1:
    def __init__(self,value):
        self._value = value
        self._children = []
    
    def myprint(self):
        print('You point value : ',self._value)
        
class Mysubtest1(Mytest1):
    def __init__(self,value,value1):
        Mytest1.__init__(self,value)
        self._value1 = value1
    
    def myprint1(self):
        print('sub class _value1 : ',self._value1)
        print('base class _value : ',self._value)   
if __name__ == '__main__':
    t = Mytest1(1)    
    t.myprint()   
    ts = Mysubtest1(1,10)
    ts.myprint1()

如果在Mysubtest1中init方法中没有调用父类的init方法的情况下是无法访问Mytest1中的_value属性的:

Traceback (most recent call last):
  File "E:\workspace\mystudy\com\dgb\object\myinit.py", line 30, in <module>
    ts.myprint1() 
  File "E:\workspace\mystudy\com\dgb\object\myinit.py", line 23, in myprint1
    print('base class _value : ',self._value)   
AttributeError: 'Mysubtest1' object has no attribute '_value'

Python3.4版本中文档:

object. __init__ ( self [, ... ] )

Called after the instance has been created (by __new__()), but before it is returned to the caller. The arguments are those passed to the class constructor expression. If a base class has an__init__() method, the derived class’s__init__() method, if any, must explicitly call it to ensure proper initialization of the base class part of the instance; for example: BaseClass.__init__(self,[args...]).

Because __new__() and __init__() work together in constructing objects (__new__() to create it, and __init__() to customise it), no non-None value may be returned by__init__(); doing so will cause aTypeError to be raised at runtime


开始系统的学习Python,从底层开始,夯实基础啊。一点一点积累。






发布了96 篇原创文章 · 获赞 22 · 访问量 31万+

猜你喜欢

转载自blog.csdn.net/chuan_day/article/details/73472686