簡體   English   中英

無需在Python中的類繼承中重新定義屬性

[英]Not having to re-define atributes in class inheritance in Python

我有這樣的事情:

Class Parent(object):
    def __init__(self, x=None):
        self.x = x

Class Child(Parent):
    def __init__(self, y):
        super(Child, self).__init__()
        self.y = y

test = Child(y=42)

效果很好:test.y等於42,而test.x等於None。 當我嘗試定義x時出現問題:

test = Child(x=32, y=42)

那顯然是行不通的。 x參數不是預期的。 我知道解決方法是:

Class Child(Parent):
    def __init__(self, x, y):
        super(Child, self).__init__(x)
        self.y = y

但是我需要對父子繼承非常深的許多變量執行此操作,我認為,在每個新的__init__中編寫所有先前的參數看起來都不是pythonic。 當然還有另一種方法,但我不知道如何。

有任何想法嗎?

一種方法是使用kwargs

class Parent(object):
    def __init__(self, x=None):
        print 'got', x
        self.x = x

class Child(Parent):
    def __init__(self, y, **kwargs):
        super(Child, self).__init__(**kwargs)
        self.y = y

子級將其自動轉發給父級:

>> test = Child(y=42)
got None
>> test = Child(y=42, x=13)
got 13

從技術上講,這是可行的,但是我不太喜歡它:

  • 子類的ctor的文檔字符串不會真正解釋期望的內容。 那很糟。

  • 如果參數的數量很少,那么最初的問題應該不會太大。 如果數量太大,則初始化參數本身可能需要形成一個類。

暫無
暫無

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

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