Python 调用类的方法时发生TypeError
我仍然得到一个错误:Python 调用类的方法时发生TypeError,python,class,Python,Class,我仍然得到一个错误: 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(se
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
的实例,然后调用该实例上的方法
Product.add(63456, 'Meow', 60.00, 0)
TypeError: unbound method add() must be called with Product instance as first argument (got int instance instead)
你的方法调用是错误的。您应该使用对象引用调用它。还有一件事,您必须将列表定义为global,这样只有您才能附加下一个元素。否则将给出名称错误:未定义全局名称“库存”错误。 试试这个:
my_product = Product(63456, 'Meow', 60.00, 0)
my_product.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
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()
您的代码包含许多错误。我认为最好在继续之前备份并阅读一篇文章。一旦你理解了Python的基本原理,你就可以继续学习更高级的课程,比如类和OOP。你指的是什么错误?没问题。如果你接受这个答案,那就太好了。:)
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()