简体   繁体   English

使用字符串来调用对象和函数

[英]Use string to call an object and function

I'm trying to take user inputs through discord and turn them into commands using imported files of my own making. 我试图通过不和谐来获取用户输入,并使用我自己制作的导入文件将它们转换为命令。 The commands follow a "XX! [object] [function] command. How do I turn an inputted string into a object? Or is there someway that I can use something similar to getattr('x', 'y')? 这些命令遵循“ XX![object] [function]命令。如何将输入的字符串转换为对象?或者某种程度上我可以使用类似于getattr('x','y')的东西?

def function():
    x = "XX! profile view"
    getattr(x.lower().split(" ")[1], x.lower().split(" ")[2])()
    return

I was hoping that would execute as profile.view(), but its giving me the error AttributeError: 'str' object has no attribute 'view'. 我希望它将作为profile.view()执行,但是它给我错误AttributeError:'str'对象没有属性'view'。

Better to not use function string names. 最好不要使用函数字符串名称。 Correct way is to create dict which match string name with function. 正确的方法是创建将字符串名称与函数匹配的字典。

def XX(*args):
    print(list(reversed(*args)))


def YY(*args):
    print(list(map(str.upper, *args)))


router = {
    "XX": XX,
    "YY": YY
}


def interpret(string):
    if any(string.startswith(key) for key in router):
        func_name = string[0: string.index("!")]
        args = string[string.index("!") + 2:].split(" ")
        router[func_name](args)


x = "YY! profile view"

interpret(x)

Perhaps you want to look into the exec() function: 也许您想研究exec()函数:

mystring = r'print("Hello World")'

exec(mystring)

>>>> Hello World

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

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