2015-10-17 37 views
1

这里是Customer类:访问数组中的元素,并呼吁他们fuctions

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 

如果我创造这样的客户对象的空列表:

customers = [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告诉我,它期望一个客户,但得到了一个int。为什么它不会自动进入这个'自我'这个arg?

但是如果我只需要创建一个客户对象,并直接调用它的方法,它工作正常:

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)给我一个错误“预期类型”客户'有int'。

+0

这不是客户的名单,这是对客户类本身的引用列表。 –

+0

是的,您客户列表的初始化不正确。您只是将“客户”类“蓝图”放入列表中,而不是真正的客户。你必须做一些像'self.customers = [Customer(1232144234,123,2)]' – dopstar

回答

2

我不确定checkout_customer居住的那个类,但我假设你在它的某个地方声明了列表self.customers。

self.costumers = []

如果您打算元素客户添加到您应该使用类似的列表:既然你想添加一个新的客户列表,这样做,你需要初始化客户类时self.customers.append(Customer(x,y,z))

我没有尝试的代码,但我相信这样的事情应该工作:

def foo(self): self.customers.append(Customer(1,'pop',2)) self.checkout_customers(23)

+0

对不起,我错了。我宣布空像这样:self.customers = [Customer]。假设我将10个客户添加到列表中。我的问题是如果我想从self.customers [0] .function1()列表中调用函数。我编辑了我原来的帖子以作进一步澄清。 – Infodayne

+1

@Infodayne感谢您的澄清。我想你应该将空数组声明为'self.costumers = []'。这样当你传递一个int时,它将返回一个costumer对象 – GSalazar