这是客户类别:
class Customer:
def __init__(self, timestamp, cid, item_count):
self.time_stamp = timestamp
self.customer_name = cid
self.item_count = item_count
def checkout(self, new_timestamp):
self.time_stamp = new_timestamp
def get_cus_name(self):
return self.customer_name
如果我创建一个空的 Customer 对象列表,例如:
customers = [Customer]
然后在其他地方我尝试在循环中调用 Customer 方法,例如:
def checkout_customer(self, cid):
for cus in self.customers:
if cus.get_cus_name == cid:
cus.checkout(self.cur_num_customers + 7)
为什么当我尝试调用 cus.checkout 时会收到错误消息?我的 ide 告诉我它需要一个 Customer,但得到了一个 int。为什么它不将自身传递到此处的“self”参数中?
但是,如果我只是创建一个 Customer 对象并直接调用它的方法,它就可以正常工作:
def foo(self):
cus = Customer(1,'pop',2)
cus.checkout(23)
这是我第一次学习 python,我一直在尝试找出列表并访问其成员。也许我的 self.custormers = [Customer]
初始化不正确?
编辑:
在测试器类的构造函数中,我创建一个像这样的空列表:
self.customer = [Customer]
我可以毫无问题地添加客户:
def add_custormer(self, customer):
self.customers.append(customer)
我的问题不是添加客户,而是在客户进入列表后访问他们的方法。做这样的事情 self.customers[0].checkout(1,'pop',2) 会给我一个错误“预期类型'Customer'得到int”。
最佳答案
我不确定 checkout_customer 所在的类,但我假设您在其中的某个位置声明了列表 self.customers 。
self.costumers = []
如果您打算将元素 Customer 添加到列表中,您应该使用类似以下内容的内容: self.customers.append(Customer(x,y,z))
因为您想添加新客户到列表中,这样做时您需要初始化 Customer 类。
我没有尝试代码,但我相信这样的东西应该有效:
def foo(自身):
self.customers.append(客户(1,'pop',2))
self.checkout_customers(23)
关于python - 访问列表元素并调用它们的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33191843/