gpt4 book ai didi

python - 类和函数范围

转载 作者:太空宇宙 更新时间:2023-11-03 18:03:27 24 4
gpt4 key购买 nike

我想根据用户输入的字符串创建类的实例,因此我使用了 exec( ) 函数。问题是我无法在函数外部通过名称访问实例。我的第一个想法是,这是函数范围的问题,我仍然认为是这样,但是当我将实例放入列表中时,我可以访问它们,只是不使用它们的名称。我不太确定这里发生了什么。有没有办法让我可以通过实例的名称访问实例,例如 thing1.properties 但在函数之外,因为这不是我的整个代码,所以它将所有内容放在函数之外会很困惑吗?比如在函数中创建实例列表并“提取”函数外部的所有实例,以便我可以在函数外部访问它们。这是代码:

class Things:
def __init__(self, properties):
self.properties = properties

listt = []
def create_instance():
exec("thing1=Things('good')")
listt.append(thing1)

create_instance()
print listt[0].properties
print thing1.properties

最佳答案

虽然我讨厌污染全局命名空间,但 exec 语句可以使用第二个参数作为范围,默认值为 locals():

>>> def foo(name):
... exec "{} = 1".format(name)
...
>>> def bar(name):
... exec "{} = 1".format(name) in globals()
...
>>> foo('a')
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> bar('a')
>>> a
1

因此,如果您传递 globals 作为作用域,它将按照您的意愿工作,但真的吗?污染全局范围本身是可怕的,在评估用户提供的代码时这样做是一种该死的责任。

[更新]

Very helpful! Thank you! But what is now better way of doing it, dictionary or a global scope?

也许您可以将所有实例存储到一个类变量中,例如:

class Thing(object):
instances = {}
def __init__(self, name, **properties):
self.name = name
self.properties = properties
self.instances[name] = self
def __repr__(self):
t = '<"{self.name}" thing, {self.properties}>'
return t.format(self=self)

现在你可以做:

# declare your things
>>> Thing('foo', a=1, b=2)
>>> Thing('bar', a=3, b=4)

# retrieve them by name
>>> Thing.instances.get('foo')
<"foo" thing, {'a': 1, 'b': 2}>

>>> Thing.instances.get('foo').properties
{'a': 1, 'b': 2}

>>> Thing.instances.get('bar').properties
{'a': 3, 'b': 4}

关于python - 类和函数范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27322598/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com