【问题标题】:Is it possible to use exec() to instantiate a class in python?是否可以使用 exec() 在 python 中实例化一个类?
【发布时间】:2015-07-05 22:01:53
【问题描述】:
class Node():
    def __init__(self, value, nex = None):
        self.value = value
        self.nex = nex

class List(Node):
    def __init__(self):
        self.head = Node(6)

    def ins(self, val):
        exec('b = Node(val)')
        self.head.nex = b

我的目的是将任何字符串设置为变量名。

【问题讨论】:

  • 我看不出有任何理由让它成为可能。 exec 语句在当前范围内执行。使用b=exec('Node(val)') 应该可以正常工作,但是这个示例没有显示使用exec 的任何附加值。您能否证明在您的案例中使用它的目的是什么?

标签: python exec eval


【解决方案1】:

显然是这样,因为您的代码可以工作(尽管我认为它并没有按照您的意愿执行,但您可能想在 List.ins() 或其他操作期间更改 List.head)。

>>> class List(Node):
...     def __init__(self):
...         self.head = Node(6)
...     def ins(self, val):
...         exec('b = Node(val)')
...         self.head.nex = b
...
>>> x = List()
>>> x.ins('a')
>>> x.head.value
6
>>> x.head.nex.value
'a'

至于将“任意字符串”设置为变量名,也可以

>>> exec ("%s = %s" % (raw_input(),raw_input()))
a
'b'
>>> a
'b'

但是你真的,真的,绝对不应该这样做(你几乎不应该使用 exec )。它实际上会使您的程序完全被劫持。如果您尝试加载配置文件或其他内容,请考虑将这些字符串用作字典键而不是变量名。 “沙盒”输入。

【讨论】:

  • 第一次使用堆栈溢出,不知道你是否能看到我的回答'@yourname',所以在这里留下评论以便你能看到。
  • 我还不能评论你的答案(新手 SO 声誉),所以关于你的答案:是的,你可以使用 setattr。不过,我不会那样做,尤其是没有像用户输入这样的东西。漏洞利用或奇怪破坏的机会太多。
【解决方案2】:

@Benny Mackney 我找到了另一种使用 setattr 的方法:

class Node():
    def __init__(self, value = None, nex = None):
        self.val = value
        self.nex = nex

class List(Node):
    def __init__(self):
        self.head = Node()

    def ins(self):
        li = []
        for i in range(10):
            setattr(self,'n' + str(i), Node(i))


        #self.n0.nex = self.n1
        #self.n1.nex = self.n2
        #self.n2.nex = self.n3
        #.
        #.
        #.
        #self.n8.nex = self.n9

所以现在我有 9 个节点,从 self.n0 到 self.n9 我如何连接它们以便我可以获得: self.head.nex = self.n0 self.n0.nex = self.n1 等等……

【讨论】:

    猜你喜欢
    • 2019-09-12
    • 1970-01-01
    • 2019-06-13
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    • 2022-08-10
    • 2020-12-13
    相关资源
    最近更新 更多