【问题标题】:Is there a way to prefix all of the functions in a python module? [duplicate]有没有办法为 python 模块中的所有函数添加前缀? [复制]
【发布时间】:2018-07-22 19:47:22
【问题描述】:

我有一个名为 foo.py 的模块,另一个模块 bar.py 从该模块将函数加载到其命名空间中。如何在 foo.py 中为所有函数添加前缀 foo_。一个例子:

foo.py:

def func1():
  return "hello"

def func2():
  return "world"

bar.py:

from foo import *

def do_something():
  return foo_func1()

【问题讨论】:

  • 为什么不直接import foo 然后foo.func1()?这是使用模块的正确方法,并且看起来与您所追求的非常相似。
  • 不要使用星号导入,这样就不会有这个名字冲突的问题。见stackoverflow.com/questions/2386714/why-is-import-bad
  • Namespaces are one honking great idea -- let's do more of those! -- The Zen of Python.

标签: python


【解决方案1】:

你在寻找这样的东西吗?

def do_something( i ):
    import foo
    f = getattr( foo, 'func'+str(i) )
    return f()

print( do_something(1) )  # hello
print( do_something(2) )  # world

您可以使用 oldfashion getattr-函数通过字符串访问属性。这将获取一个对象和一个 string,您可以在运行时创建它们。

文档:getattr(object, name[, default])


编辑(抱歉,完全看错了问题)

你可以简单地使用

import foo

然后调用函数:

foo.funct1()  # hello
foo.funct2()  # world

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-21
    • 2017-01-02
    • 2023-03-15
    • 1970-01-01
    • 2014-04-16
    相关资源
    最近更新 更多