【问题标题】:Accessing elements of lists, and calling their fuctions访问列表元素并调用它们的函数
【发布时间】:2015-10-17 21:36:18
【问题描述】:

这是客户类:

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]

然后我尝试在其他地方循环调用 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。为什么它不在这里将自己传递给“自我”arg?

但是,如果我只是创建一个 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' got int”。

【问题讨论】:

  • 这不是客户列表,而是对 Customer 类本身的引用列表。
  • 是的,您对customers 列表的初始化不正确。您只是将Customer 类“蓝图”放在列表中,它不是真正的客户。你必须做类似self.customers = [Customer(1232144234, 123, 2)]

标签: python arrays list python-3.x generics


【解决方案1】:

我不确定 checkout_customer 所在的类,但我假设您在其中的某处声明了 self.customers 列表。

self.costumers = []

如果您打算将元素 Customer 添加到列表中,您应该使用类似:self.customers.append(Customer(x,y,z)),因为您想要将新客户添加到列表中,并且在这样做时您需要初始化 Customer 类。

我没有尝试代码,但我相信这样的东西应该可以工作:

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

【讨论】:

  • 对不起,我弄错了。我像这样声明为空:self.customers = [Customer]。假设我将 10 个客户添加到列表中。我的问题是如果我想从 self.customers[0].function1() 之类的列表中调用函数。我编辑了我的原始帖子以进一步澄清。
  • @Infodayne 感谢您的澄清。我认为您应该将空数组声明为self.costumers = []。这样,当您传递一个 int 时,它将返回一个客户对象
猜你喜欢
  • 2023-03-14
  • 2018-02-03
  • 2013-08-17
  • 2011-12-30
  • 2013-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多