简体   繁体   English

Python 方法:使用变量作为 object 的参数

[英]Python Method: Using a variable as an argument of a object

I have a object, that can have some types of arguments, like:我有一个 object,它可以有一些类型的 arguments,比如:

myObject.goUp

myObject.goDown

myObject.goLeft

myObject.goRight

I wish to use a variable to specify which object I am using, like:我希望使用一个变量来指定我正在使用哪个 object,例如:

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.如果在 object 中找不到该方法,这将抛出AttributeError ,因此请务必处理这种情况。

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.如果上面是您的问题,那么我们不能使用这种方式,因为一个 class 中存在的每种方法都有唯一的名称,如果要使用该方法,那么我们可以通过其原始名称访问。

I hope your doubt is now clear.我希望你的疑问现在清楚了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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