In Python, how do I change which class's attribute a function will look for based on a parameter?

40 views Asked by At

I'd like to use the same function twice but change which class attribute the function will use. It would look similiar to below:

class Player:
    def __init__(self):
        self.primary_color = 'blue'
        self.secondary_color = 'pink'

    def show_color(self, color_attribute)
        print(color_attribute)

player = Player

print(player.show_color(primary_color))
>>>'blue'
print(player.show_color(secondary_color))
>>>'pink'

This particular color example may not be very helpful but the project I'm working on would greatly benefit from this ability.

1

There are 1 answers

0
e.Fro On

In this case, the function show_color should rather be static, since it does not use the class attributes directly. A fast solution would be to pass the attributes directly to the function:

player = Player()
print(player.show_color(player.primary_color))
>>>'blue'
print(player.show_color(player.secondary_color))
>>>'pink'

But as I said, then the function does not make much sense inside the Player class. Depending on your final use case, you can access the attribute directly:

print(player.primary_color)
>>>'blue'
print(player.secondary_color)
>>>'pink'