[英]How to check which function has been returned in python?
I have two methods which take different number of arguments. Here are the two functions:我有两种方法采用不同数量的 arguments。这是两个函数:
def jumpMX(self,IAS,list):
pass
def addMX(self,IAS):
pass
I am using a function which will return one of these functions to main.I have stored this returned function in a variable named operation.我正在使用 function,它将这些函数之一返回给 main。我已将返回的 function 存储在一个名为 operation 的变量中。 Since the number of parameters are different for both,how do I identify which function has been returned?
由于两者的参数个数不同,如何识别返回的是哪个function?
if(operation == jumpMX):
operation(IAS,list)
elif(operation == addMX):
operation(IAS)
What is the syntax for this?Thanks in advance!这个的语法是什么?提前致谢!
You can identify a function through its __name__
attribute:您可以通过其
__name__
属性识别 function:
def foo():
pass
print(foo.__name__)
>>> foo
...or in your case: ...或者你的情况:
operation.__name__ #will return either "jumpMX" or "addMX" depending on what function is stored in operation
Here's a demo you can modify to your needs:这是一个演示,您可以根据需要进行修改:
import random #used only for demo purposes
def jumpMX(self,IAS,list):
pass
def addMX(self,IAS):
pass
def FunctionThatWillReturnOneOrTheOtherOfTheTwoFunctionsAbove():
# This will randomly return either jumpMX()
# or addMX to simulate different scenarios
funcs = [jumpMX, addMX]
randomFunc = random.choice(funcs)
return randomFunc
operation = FunctionThatWillReturnOneOrTheOtherOfTheTwoFunctionsAbove()
name = operation.__name__
if(name == "jumpMX"):
operation(IAS,list)
elif(name == "addMX"):
operation(IAS)
You can import those functions and test for equality like with most objects in python.您可以像 python 中的大多数对象一样导入这些函数并测试是否相等。
classes.py类.py
class MyClass:
@staticmethod
def jump(self, ias, _list):
pass
@staticmethod
def add(self, ias):
pass
main.py主程序
from classes import MyClass
myclass_instance = MyClass()
operation = get_op() # your function that returns MyClass.jump or MyClass.add
if operation == MyClass.jump:
operation(myclass_instance, ias, _list)
elif operation == MyClass.add:
operation(myclass_instance, ias)
However, I must emphasize that I don't know what you're trying to accomplish and this seems like a terribly contrived way of doing something like this.但是,我必须强调,我不知道你想要完成什么,这似乎是一种非常人为的方式来做这样的事情。
Also, your python code examples are not properly formatted.此外,您的 python 代码示例格式不正确。 See the PEP-8 which proposes a standard style-guide for python.
请参阅PEP-8 ,它提出了 python 的标准样式指南。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.