簡體   English   中英

Python類和__init__方法

[英]Python classes and __init__ method

我正在通過深入python學習python。 即使通過文檔,也幾乎沒有問題也無法理解。

1) BaseClass

2) InheritClass

InheritClass不包含__init__方法和BaseClass時,我們將一個InheritClass實例分配給一個變量時到底發生了什么?

  • 是否自動調用BaseClass __init__方法
  • 另外,告訴我在引擎蓋下發生的其他事情。

實際上fileInfo.py的例子讓我很頭疼,我只是無法理解事情是如何運作的。 以下

是的,將自動調用BaseClass.__init__ 父類中定義的任何其他方法也是如此,但子類不是。 注意:

>>> class Parent(object):
...   def __init__(self):
...     print 'Parent.__init__'
...   def func(self, x):
...     print x
...
>>> class Child(Parent):
...   pass
...
>>> x = Child()
Parent.__init__
>>> x.func(1)
1

孩子繼承了父母的方法。 它可以覆蓋它們,但它不必。

@FogleBird已經回答了你的問題,但我想添加一些東西,不能對他的帖子發表評論:

您可能還想查看super函數 這是一種從孩子內部調用父方法的方法。 當您想要擴展方法時,它會很有用,例如:

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

class ChildClass(ParentClass):
    def __init__(self, x, y):
        self.y = y
        super(ChildClass, self).__init__(x)

這當然可以包含更復雜的方法, 而不是 __init__方法,甚至是同名的方法!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM