我正在尝试找到一种通过名称访问模块变量的方法,但还没有找到任何东西.我现在使用的是:
var = eval('myModule.%s' % (variableName))
Run Code Online (Sandbox Code Playgroud)
但它是模糊的,并打破IDE错误检查(即在eclipse/pydev导入myModule标记为未使用,而上面的行需要它).有没有更好的方法呢?可能是模块内置函数我不知道?
def test():
print 'test'
def test2():
print 'test2'
test = {'test':'blabla','test2':'blabla2'}
for key, val in test.items():
key() # Here i want to call the function with the key name, how can i do so?
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用函数返回给定列表.
def get_ext(file_type):
text = ['txt', 'doc']
audio = ['mp3', 'wav']
video = ['mp4', 'mkv']
return ?????
get_ext('audio') #should return de list ['mp3', 'wav']
Run Code Online (Sandbox Code Playgroud)
然后我被卡住了.这是一个扩展列表的简单/简短示例.最简单的方法是什么?
我试图从类中的方法动态创建模块级函数.因此,对于类中的每个方法,我想创建一个具有相同名称的函数,该函数创建类的实例,然后调用该方法.
我想这样做的原因是我可以采用面向对象的方法来创建Fabric文件.由于Fabric将调用模块级函数而不是类的方法,因此这是我的解决方法.
我使用以下链接让我开始
我提出了以下代码
import inspect
import sys
import types
class TestClass(object):
def __init__(self):
pass
def method1(self, arg1):
print 'method 1 %s' % arg1
def method2(self):
print 'method 2'
def fabric_class_to_function_magic(module_name):
# get the module as an object
print module_name
module_obj = sys.modules[module_name]
print dir(module_obj)
# Iterate over the methods of the class and dynamically create a function
# for each method that calls the method and add it to the current module
for …Run Code Online (Sandbox Code Playgroud) 我需要做的是循环大量不同的文件并(尝试)从文件中获取元数据.
我可以创建一个大的if ... elif ...并测试每个扩展,但我认为将扩展存储在变量中会更容易,检查是否存在具有该名称的函数,然后执行它.
这是我目前的解决方案,取自另一个stackoverflow线程:
try:
getattr(modulename, funcname)(arg)
except AttributeError:
print 'function not found "%s" (%s)' % (funcname, arg)
Run Code Online (Sandbox Code Playgroud)
这有一个问题:如果底层函数引发了AttributeError,则会将其注册为"找不到函数"错误.我可以添加try ...除了块到所有函数,但这也不是特别漂亮......
我正在寻找的更像是:
if function_exists(fun):
execute_function(fun, arg)
Run Code Online (Sandbox Code Playgroud)
有这么简单的方法吗?
谢谢 :-)
在Python中使用函数名称的字符串调用模块的函数向我们展示了如何使用getattr(" bar ")()调用函数,但这假设我们已经导入了模块foo.
假如我们可能还必须执行foo的导入(或者从bar import foo),那么我们怎么会去调用"foo.bar"的执行呢?
可能重复:
在Python中使用函数名称从字符串调用函数
我想我可以编写一些可怕的代码,但我更愿意看到'干净版'.
对我来说似乎最好的方法是创建一个包含给定对象可以使用的各种函数的dict.然后,当指示用户告诉对象它在做什么时,它会根据该字典吐出一个菜单.
我搜索了一下,并没有真正看到适合我的东西,所以我想我试一试.嗯,它不起作用.
class Man(object):
def __init__(self):
self.cmds = ['foo', 'bar']
def foo(self):
print "Foo called."
def bar(self):
print "Bar called."
def junk(self):
print "Junk called." ##not in dict, on purpose, will explain
def menu(self):
while True:
print "List of actions:"
for acts in self.cmds:
print acts
cmd = raw_input("> ")
if cmd in self.cmds:
cmd() ##doesn't work.
##neither did self.cmd() (got AttributeError, obviously)
result = getattr(self, cmd)() ## this works! thanks cdhowie
else:
pass
Stick = Man() …Run Code Online (Sandbox Code Playgroud) 我有几个功能,如:
def func1():
print 'func1'
def func2():
print 'func2'
def func3():
print 'func3'
Run Code Online (Sandbox Code Playgroud)
然后我要求用户输入他们想要运行choice = raw_input()的功能,并尝试调用他们使用的功能choice().如果用户输入func1而不是调用该函数,则会给出一个错误'str' object is not callable.无论如何,他们是否将"选择"转变为可赎回价值?
我需要的是获取变量的东西,如果变量是函数的名称,则将调用该函数.我不是试图从模块中获取函数,而是从程序本身中获取函数
例:
def foo():
print("Foo")
callfunction = input("What function do you want to call? ")
callfunction() ## Not sure what to put here but but lets say callfunction is foo.
Run Code Online (Sandbox Code Playgroud)
我不想要这样的东西,因为我有很多功能:
if callfunction == "Foo"
Foo()
else:
print("No function with that name")
Run Code Online (Sandbox Code Playgroud)
我的问题是这样的,但我要求Python语法.我使用的是Python 3.5.1
我知道使用globals(),locals()和getattr通过字符串来反馈Python中的内容(如本问题所示),但除非我遗漏了一些明显的东西,否则我似乎无法使用它来调用类型.
例如:
In [12]: locals()['int']
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
e:\downloads_to_access\<ipython console> in <module>()
KeyError: 'int'
In [13]: globals()['int']
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
e:\downloads_to_access\<ipython console> in <module>()
KeyError: 'int'
getattr(???, 'int')...
Run Code Online (Sandbox Code Playgroud)
这样做的最佳方法是什么?
python ×10
function ×2
dictionary ×1
fabric ×1
getattr ×1
list ×1
menu ×1
module ×1
python-3.x ×1
variables ×1