0

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

Hero
  • 3
  • 2
  • Warnings like these are usually due to breaking PEP 8 convention, over making things that will break your code. Usually it's a good idea to follow convention, but sometimes you go around it for your own custom reasons. In this case, you should probably just follow convention. Your code will work but it's recommended to do it the right way for reusability and scalability. – OakenDuck Feb 03 '21 at 03:29

2 Answers2

1

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.
pakpe
  • 5,391
  • 2
  • 8
  • 23
0

I upvoted the other answer, what pakpe gave is how the code should look at the end. There was a design problem indead.

With that in mind, your basic problem is that an instance method should have 'self' as first argument. If you want a static function you should decorate it with staticmethod:

Ie:

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

customer = Customer()
customer.print_all_customers(customers)

Or:

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

Customer.print_all_customers(customers)

Without @staticmethod, we expect the first argument to be self ie a Customer instance, not a list. See also Difference between staticmethod and classmethod

Pierre.Sassoulas
  • 3,733
  • 3
  • 33
  • 48