istupidguy
istupidguy

Reputation: 23

python For loop for class attributes?

Is there a way i can loop a function with an argument in a class if that argument is not equal to None? I know how to do this with a lot of if loops, but is there another way I can do this?

Here's an example of what I want to do:

class Name:
    def __init__(self,name,favfood,favcolour,favsport):
        self.name = name
        self.favfood = favfood
        self.favcolour = favcolour
        self.favsport = favsport

henry = Name("Henry","Sushi","Blue",None)

I want a function that prints out all his favourite things, but will skip it if it is None, a for loop for classes pretty much.

Is there a way to have a forloop for every attribute in a class?

Upvotes: 0

Views: 3261

Answers (2)

vash_the_stampede
vash_the_stampede

Reputation: 4606

*Updated Would use the __dict__ attribute as @blhsing suggested

class Name:
    def __init__(self,name,favfood,favcolour,favsport):
        self.name = name
        self.favfood = favfood
        self.favcolour = favcolour
        self.favsport = favsport

    def print_favs(self):
        '''even better using @blh method'''
        [print(f'{k}: {v}') for k, v in self.__dict__.items() if v != None]



henry = Name("Henry","Sushi","Blue",None)
henry.print_favs()
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 helping.py 
name: Henry
favfood: Sushi
favcolour: Blue

Upvotes: 0

blhsing
blhsing

Reputation: 106445

You can use the __dict__ attribute of the self object:

class Name:
    def __init__(self,name,favfood,favcolour,favsport):
        self.name = name
        self.favfood = favfood
        self.favcolour = favcolour
        self.favsport = favsport
        for key, value in self.__dict__.items():
            if value is not None:
                print('%s: %s' % (key, value))

henry = Name("Henry","Sushi","Blue",None)

This outputs:

name: Henry
favfood: Sushi
favcolour: Blue

Upvotes: 1

Related Questions