1. 程式人生 > >python2,python3子類呼叫父類初始化函式的方法和注意事項

python2,python3子類呼叫父類初始化函式的方法和注意事項

python2、python3:

python子類呼叫父類初始化函式有兩種方式,以下程式碼在python2和python3都能執行:

class A(object):
    def __init__(self, x):
        self.x = x

# 方法一
class B(A):
    def __init__(self, x, y):
        A.__init__(self, x)
        self.y = y

# 方法二
class C(A):
    def __init__(self, x, y):
        super(C, self).__init__
(x) self.y = y b = B('foo', 'bar') c = C('foo', 'bar') print(b.x, b.y) print(c.x, c.y)

python2:

第二方法,在python2中父類A要繼承objectt類,否則會出錯:

>>> class A:
    def __init__(self, x):
        self.x = x

>>> class C(A):
    def __init__(self, x, y):
        super(C, self).__init__
(x) self.y = y >>> c = C('foo', 'bar')
Traceback (most recent call last): File "<pyshell#167>", line 1, in <module> b = B('foo', 'bar') File "<pyshell#166>", line 3, in __init__ super(B, self).__init__(x) TypeError: super() argument 1 must be type, not
classobj
>>>

python3:

第二方法,在python3中父類A可以不繼承object,因為python3中類都是預設繼承object的:

>>> class A:
    def __init__(self, x):
        self.x = x

>>> class C(A):
    def __init__(self, x, y):
        super(C, self).__init__(x)
        self.y = y

>>> c = C('foo', 'bar')
>>> print(c.x, c.y)
foo bar
>>>

其中super的引數可以省略,程式碼簡化為:

>>> class A:
    def __init__(self, x):
        self.x = x

>>> class C(A):
    def __init__(self, x, y):
        super().__init__(x)
        self.y = y

>>> c = C('foo', 'bar')
>>> print(c.x, c.y)
foo bar
>>>