0

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?

istupidguy
  • 23
  • 1
  • 3

2 Answers2

1

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
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • is there a way to use the key variable as an attribute? For example, i can call the attribute with henry.key – istupidguy Sep 20 '18 at 14:12
  • The only problem is that not all objects have a `__dict__` attribute... When a class defines a `__slots__` attribute, its objects have no `__dict__`. – Serge Ballesta Sep 20 '18 at 14:45
0

*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
vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20
  • Don't. `self.lista` contains the original values of the attributes. If an attribute receives a new value, `self.lista` will remain unchanged. – Serge Ballesta Sep 20 '18 at 14:49