0

I have a object, that can have some types of arguments, like:

myObject.goUp

myObject.goDown

myObject.goLeft

myObject.goRight

I wish to use a variable to specify which object I am using, like:

variable = goUp

myObject.variable

It is possible? Thank in advance!

kuro
  • 3,214
  • 3
  • 15
  • 31
ManuS
  • 17
  • 3
  • 1
    Are `goUp`, `goDown` etc. the member functions of the class? Can you show the class definition? – kuro Nov 04 '19 at 10:26
  • You probably mean attributes not arguments – Gnudiff Nov 04 '19 at 10:46
  • Does this answer your question? [Python: access class property from string](https://stackoverflow.com/questions/1167398/python-access-class-property-from-string) – Gnudiff Nov 04 '19 at 10:49

2 Answers2

1

Maybe this will do the trick:

variable = 'goUp'
callable = getattr(myObject, variable)
callable()

This will throw AttributeError if the method is not found in the object, so be sure to handle that case.

fixmycode
  • 8,220
  • 2
  • 28
  • 43
-1

In your question i think you want to say, can we access the method by some other name.

If above is your question then,No we can not use this way because every method that are present in one class have unique name and if want to use that method so we have access by its original name that.

I hope your doubt is now clear.