2015-05-19 35 views
1

子類一類我有下面的類Python27:通過使用類型

class Sample(object): 
    def __init__(self, argument, argument2, argument3): 
     self.value = argument 
     self.value2 = argument2 
     self.value3 = argument3 

,我想用創建的這個子類但我不知道如何來填充參數的__ init __方法。

我也有這個習俗__的init __方法,填充物:

def setup(self, arg, arg2, arg3): 
    self.value = "good" 
    self.value2 = "day" 
    self.value3 = "sir" 

myclass = type("TestSample", (Sample,), dict(__init__=setup)) 

但是當我執行:

myclass() 

我得到:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: setup() takes exactly 4 arguments (1 given) 

是有一種預先填充這些值的方法,而不必在obj提供它們等等instatiation?

+1

您可能在尋找默認參數,寫爲'def f(x = 1,y = 2,...):(...)'。但請注意,這些變化是可變的,例如如果您使用容器類型(列表,字典,集合等)作爲默認參數併爲其添加值,則它在下次調用時仍將具有該值。 – l4mpi

+0

哦!所以如果我提供默認參數,那麼由於改變的__init__方法它們不會生效?我給了一個去 – Har

回答

2

你的子類工作正常,但你給了它自己的__init__方法,仍然需要四個位置參數。其中之一是self,但你仍然需要提供其他3創建對象時:

myclass('some', 'argument', 'values') 

你的功能忽略這些參數,否則,也許你的意思是不包括他們在函數簽名?你不必在這裏父類匹配:

def setup(self): 
    self.value = "good" 
    self.value2 = "day" 
    self.value3 = "sir" 

myclass = type("TestSample", (Sample,), dict(__init__=setup)) 

直接設置屬性相反,你可以委派給父類還是:

def setup(self): 
    Sample.__init__(self, 'good', 'day', 'sir') 

myclass = type("TestSample", (Sample,), dict(__init__=setup)) 

如果你想這是默認你可以重寫,使用關鍵字參數:

def setup(self, argument='good', argument2='day', argument3='sir'): 
    Sample.__init__(self, argument, argument2, argument3) 

myclass = type("TestSample", (Sample,), dict(__init__=setup)) 

現在,你可以省略參數,或者提供個不同的值em:

c1 = myclass() 
c2 = myclass(argument2='weekend') 
+0

爲什麼如果我做了部分設置不工作?即dict(__ init __ = partial(setup,argument =「good」,argument2 =「day」,argument3 =「sir」)),同時刪除默認參數。這不等同於第一個和第二個安裝示例嗎? – Har

+1

@Har:'functools.partial()'對象不實現描述符協議,因此不能用作方法。 Python 3.4增加了一個['partialmethod'對象](https://docs.python.org/3/library/functools.html#functools.partial方法)* * *。 –

+0

謝謝。我之前曾經遇到過描述符協議,但我想看看它 – Har