2011-02-01 20 views
1

我有一個方法在我的Customer類中調用save_from_row()。它看起來像這樣:Python noob不能得到類方法工作

@classmethod 
def save_from_row(row): 
    c = Customer() 
    c.name = row.value('customer', 'name') 
    c.customer_number = row.value('customer', 'number') 
    c.social_security_number = row.value('customer', 'social_security_number') 
    c.phone = row.value('customer', 'phone') 
    c.save() 
    return c 

當我嘗試運行我的腳本,我得到這個:

Traceback (most recent call last): 
    File "./import.py", line 16, in <module> 
    Customer.save_from_row(row) 
TypeError: save_from_row() takes exactly 1 argument (2 given) 

我不明白,在參數的數目不匹配。這是怎麼回事?

回答

13

classmethod的第一個參數是類本身。嘗試

@classmethod 
def save_from_row(cls, row): 
    c = cls() 
    # ... 
    return c 

@staticmethod 
def save_from_row(row): 
    c = Customer() 
    # ... 
    return c 

classmethod變異將使用同一個工廠函數來創建的Customer子類。

而不是staticmethod變體,我通常會使用模塊級功能。

+0

通過模塊級別的功能,你可以使用任何模型?這就是我最終希望做的。無論如何,這爲我修好了。謝謝。 – 2011-02-01 17:37:50

5

你想:

@classmethod 
def save_from_row(cls, row): 

類方法獲得方法的類作爲第一個參數。