【问题标题】:Create python function with name from array [duplicate]使用数组中的名称创建python函数[重复]
【发布时间】:2019-12-23 00:42:47
【问题描述】:

我想创建函数 (def $name:),其中名称来自 array=['str1', 'str2', ...]。

我尝试了上面的代码,已经在 stackoverflow 和 google 上搜索过,但没有找到任何解决方案。

array = ['String1', 'String2', ...]

def array[0]:

     code1

def array[1]:
     code2

String1()
String2()

【问题讨论】:

  • @Axium 这不是 不可能 它只是 非常不可取
  • 不要这样做。 Python != PHP 并没有为您提供任何创建可变变量的好方法。只需使用容器,如列表或字典。
  • 除了欺骗目标之外,您还可以(并且应该)将函数存储在任何数据结构中:[f1, f2]
  • 这是一个有趣的问题:)。

标签: python arrays function


【解决方案1】:

您不能使用变量定义函数。但事实证明,你可以重新绑定函数变量名。

看到这个帖子: How to use a variable as function name in Python

如何做到这一点的示例:

one = 'one'
two = 'two'
three = 'three'
l = [one, two, three]
def some_stuff():
    print("i am sure some stuff")
for item in l:
    def _f():
        some_stuff()
    globals()[item] = _f
    del _f

one()
two()
three()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-25
    • 2013-05-10
    • 2023-03-22
    • 2011-03-31
    相关资源
    最近更新 更多