2015-10-17 38 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