Search code examples
pythonpython-3.xpylint

how to avoid pylint(not-an-iterable) in this code?


similar: question: How to avoid pylint not-an-iterable when using a custom property class

I just started coding and didn't understand the code above

This code is working but I'm getting two warning errors in 2nd def

1,pylint(no-self-argument) (but i'm using it on class)

2,pylint(not-an-iterable) (on the customerlist in 2nd def)

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)

how to avoid these errors in this code, please explain in simple words


Solution

  • There are two main problems with your code. First, you need a string method that provides a string representation of your Customer object so you can print it. Second, your print_all_customers() function should be outside your class -- it is not an appropriate class method. Fixing up your code also gets rid of pylint errors.

    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.