可以用exec()在python中实例化一个类吗?

2024-04-27 19:19:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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


Tags: 字符串self目的nonenodeinitvaluedef
2条回答

显然是这样的,因为你的代码是有效的(虽然我不认为它做了你想要它做的,你可能想要改变列表.head期间列表.ins()什么的)。在

>>> 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'

至于将“any string”设置为变量名,也可以

^{pr2}$

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

@本尼·麦克尼 我找到了另一种方法,使用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=自身n0 self.n0.nex=self.n1 等。。。在

相关问题 更多 >