2014-12-23 68 views
-1
class Product(object): 

def __init__(self, ind, name, price, quantity): 

    self.ind = ind 
    self.name = name 
    self.price = price 
    self.quantity = quantity 


inventory = list() 


def add(self): 


    inventory.append(Product(self.ind)) 
    inventory.append(Product(self.name)) 
    inventory.append(Product(self.price)) 
    inventory.append(Product(self.quantity)) 
    print('product %s added')%name 

Product.add(63456, 'Meow', 60.00, 0) 

我仍然得到一個錯誤的方法時:類型錯誤調用類

Product.add(63456, 'Meow', 60.00, 0) 
TypeError: unbound method add() must be called with Product instance as first argument (got int instance instead) 

,我不知道,因爲我剛開始學習班什麼是錯。

什麼需要改變?

+1

你的代碼中包含大量的錯誤。我認爲最好是在繼續之前備份並閱讀[基本Python教程](https://docs.python.org/3/tutorial/index.html)。一旦理解了Python的基礎知識,就可以繼續學習更高級的主題,如類和OOP。 – iCodez

+0

你是指什麼錯誤? – Iwko

回答

0

您的方法調用錯誤。你應該用對象引用來調用它。還有一件事你必須定義你的名單爲全球然後只有你將能夠追加下一個元素。否則它會給NameError:沒有定義全局名稱'inventory'錯誤。 嘗試了這一點:

class Product(object): 

    def __init__(self, ind, name, price, quantity): 
     self.ind = ind 
     self.name = name 
     self.price = price 
     self.quantity = quantity   

    global inventory 
    inventory = [] 

    def add(self): 
     inventory.append(self.ind) 
     inventory.append(self.name) 
     inventory.append(self.price) 
     inventory.append(self.quantity) 
     print('product %s added')% self.name 

obj = Product(63456, 'Meow', 60.00, 0) 
obj.add() 

,或者如果你想有庫存的單獨副本的每個對象,然後定義庫存爲self.inventory = [] 因此你的代碼看起來是這樣的:

class Product(object): 

    def __init__(self, ind, name, price, quantity): 
     self.ind = ind 
     self.name = name 
     self.price = price 
     self.quantity = quantity   
     self.inventory = [] 


    def add(self): 
     self.inventory.append(self.ind) 
     self.inventory.append(self.name) 
     self.inventory.append(self.price) 
     self.inventory.append(self.quantity) 
     print('product %s added')% self.name 

obj = Product(63456, 'Meow', 60.00, 0) 
obj.add() 
+0

非常感謝!你幫了我很多。 – Iwko

+0

沒問題。如果你接受答案會很好。 :) –

0

您正在調用該方法,就好像它是靜態方法一樣。這是一個實例方法。您需要創建Product的實例,然後在該實例上調用該方法。

my_product = Product(63456, 'Meow', 60.00, 0) 
my_product.add()