0

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.

  • What exactly can be the argument for `show_color`? An arbitrary string, a one of specially prepared constants, something else? – yeputons Dec 28 '21 at 22:36

1 Answers1

0

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'

e.Fro
  • 387
  • 1
  • 14