python - 访问列表元素并调用它们的函数

标签 python arrays list python-3.x generics

这是客户类别:

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/

相关文章:

python - Pandas Dataframe 中的缺失值填写错误

java - 从java中的字符串中找到第一个唯一字符

list - F# - 创建程序来读取文件并反向打印,如何删除所有新行引号?

python - 如何将 Flask 应用程序连接到在 Docker 中运行的 SQLite DB?

php - 有哪些工具可用于可视化类内依赖关系(例如 PHP)?

python - 如何在没有 Pandas 的情况下在 Python 中处理 csv 文件

javascript - 过滤数组但 Item 被跳过

arrays - 使用 Powershell "where"命令与值数组进行比较

java - 如何使用泛型在 Java 中将 List<?> 转换为 List<T>?

python - 想要找到一种对多个列表进行平均的方法