简体   繁体   中英

Python Method: Using a variable as an argument of a object

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!

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM