相关疑难解决方法(0)

python按名称获取模块变量

我正在尝试找到一种通过名称访问模块变量的方法,但还没有找到任何东西.我现在使用的是:

var = eval('myModule.%s' % (variableName))
Run Code Online (Sandbox Code Playgroud)

但它是模糊的,并打破IDE错误检查(即在eclipse/pydev导入myModule标记为未使用,而上面的行需要它).有没有更好的方法呢?可能是模块内置函数我不知道?

python variables module

14
推荐指数
2
解决办法
7879
查看次数

python函数调用变量

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)

python

11
推荐指数
3
解决办法
4万
查看次数

从Python中的函数返回名称中的变量

我正在尝试使用函数返回给定列表.

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)

然后我被卡住了.这是一个扩展列表的简单/简短示例.最简单的方法是什么?

python function list

11
推荐指数
2
解决办法
3696
查看次数

如何从类中的方法动态创建模块级函数

我试图从类中的方法动态创建模块级函数.因此,对于类中的每个方法,我想创建一个具有相同名称的函数,该函数创建类的实例,然后调用该方法.

我想这样做的原因是我可以采用面向对象的方法来创建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)

python metaprogramming fabric

9
推荐指数
1
解决办法
6853
查看次数

在Python中通过变量名执行函数

我需要做的是循环大量不同的文件并(尝试)从文件中获取元数据.

我可以创建一个大的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

9
推荐指数
1
解决办法
2万
查看次数

如何在python中处理字符串调用模块和函数?

在Python使用函数名称的字符串调用模块的函数向我们展示了如何使用getattr(" bar ")()调用函数,但这假设我们已经导入了模块foo.

假如我们可能还必须执行foo的导入(或者从bar import foo),那么我们怎么会去调用"foo.bar"的执行呢?

python

6
推荐指数
1
解决办法
2201
查看次数

用Python制作菜单

可能重复:
在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)

python dictionary menu

6
推荐指数
1
解决办法
2775
查看次数

如何使用用户输入在Python中调用函数?

我有几个功能,如:

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.无论如何,他们是否将"选择"转变为可赎回价值?

python function

6
推荐指数
2
解决办法
9134
查看次数

从Python中存储的字符串调用函数

我需要的是获取变量的东西,如果变量是函数的名称,则将调用该函数.我不是试图从模块中获取函数,而是从程序本身中获取函数

例:

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

python python-3.x

6
推荐指数
3
解决办法
5776
查看次数

在Python中通过名称作为字符串调用类型

我知道使用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 getattr

5
推荐指数
2
解决办法
1948
查看次数