這裏是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'。
這不是客戶的名單,這是對客戶類本身的引用列表。 –
是的,您客戶列表的初始化不正確。您只是將「客戶」類「藍圖」放入列表中,而不是真正的客戶。你必須做一些像'self.customers = [Customer(1232144234,123,2)]' – dopstar