python - Class and function scope -
i want create instances of class string user has typed in used exec( ) function. problem can't access instance name outside function. first thought problem scope of function, , still think when put instances in list can access them, not using name. i'm not sure happening here.. there way access instances name, thing1.properties
outside function because not whole code messy put outside function? create list of instances in function , "extract" instances outside function access them outside function. here code:
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
while abhor polluting global namespace, exec statement can take second argument used scope , defaults locals()
:
>>> def foo(name): ... exec "{} = 1".format(name) ... >>> def bar(name): ... exec "{} = 1".format(name) in globals() ... >>> foo('a') >>> traceback (most recent call last): file "<stdin>", line 1, in <module> nameerror: name 'a' not defined >>> bar('a') >>> 1
so if pass globals
scope, work want, really? polluting global scope horrid, doing while evaluating user supplied code damn liability.
[update]
very helpful! thank you! better way of doing it, dictionary or global scope?
perhaps can store instances class variable, example:
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)
now can do:
# declare things >>> thing('foo', a=1, b=2) >>> thing('bar', a=3, b=4) # retrieve them 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}
Comments
Post a Comment