如何避免这段代码中的 pylint(不可迭代)?

问题描述 投票:0回答:2

类似:问题:使用自定义属性类时如何避免 pylint 不可迭代

我刚刚开始编码,不明白上面的代码

此代码有效,但我在第二个 def 中收到两个警告错误

1,pylint(无自辩)(但我在课堂上使用它)

2,pylint(不可迭代)(在第二个定义的客户列表中)

class Customer:
    def __init__(self, name, membership_type):
        self.name = name
        self.membership_type = membership_type
    def print_all_customers(customerlist):
        for customer in customerlist:
            print(customer,'\n')

customerlist = [Customer('shagun','gold'),Customer('hero','diamond'),Customer('sid','gold')]
Customer.print_all_customers(customerlist)

如何避免这段代码中的这些错误,请用简单的话解释一下

python python-3.x pylint
2个回答
1
投票

您的代码有两个主要问题。首先,您需要一个字符串方法来提供 Customer 对象的字符串表示形式,以便您可以打印它。其次,你的 print_all_customers() 函数应该在你的类之外——它不是一个合适的类方法。修复代码也可以消除 pylint 错误。

class Customer:
    def __init__(self, name, membership_type):
        self.name = name
        self.membership_type = membership_type

    def __str__(self) -> str:
        return f'Customer {self.name} is a {self.membership_type} member.'

def print_all_customers(lst):
    for customer in lst:
        print(customer)

customerlist = [Customer('shagun','gold'),Customer('hero','diamond'),Customer('sid','gold')]
print_all_customers(customerlist)

#prints:
#Customer shagun is a gold member.
#Customer hero is a diamond member.
#Customer sid is a gold member.

0
投票

我赞成另一个答案,pakpe给出的是代码最后应该是什么样子。确实存在设计问题。

考虑到这一点,您的基本问题是实例方法应该将“self”作为第一个参数。如果你想要一个静态函数,你应该用 staticmethod 来装饰它:

即:

class Customer:
    def print_all_customers(self, customers):
        ...

customer = Customer()
customer.print_all_customers(customers)

或者:

class Customer:
    @staticmethod
    def print_all_customers(customers):
        ...

Customer.print_all_customers(customers)

如果没有

@staticmethod
,我们期望第一个参数是
self
,即 Customer 实例,而不是列表。另请参阅静态方法和类方法之间的区别

© www.soinside.com 2019 - 2024. All rights reserved.