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?

1
  • 3
    https://stackoverflow.com/questions/6886493/get-all-object-attributes-in-python Commented Sep 20, 2018 at 13:35

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

is there a way to use the key variable as an attribute? For example, i can call the attribute with henry.key
The only problem is that not all objects have a __dict__ attribute... When a class defines a __slots__ attribute, its objects have no __dict__.
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

1 Comment

Don't. self.lista contains the original values of the attributes. If an attribute receives a new value, self.lista will remain unchanged.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.