Cool object trick

Robert Brewer fumanchu at amor.org
Fri Dec 17 17:18:10 CET 2004


Alex Stapleton wrote:
> you can't do
>
> var = "varA"
> obj = struct(varA = "Hello")
> print obj.var
>
> and expect it to say Hello to you.

Did you mean "print obj.varA"? I can't think of any use case for the way
you wrote it, so I'm naively guessing you've got a typo. Feel free to
correct me. ;)

>>> class struct(object):
... 	def __init__(self, **kwargs):
... 		self.__dict__.update(kwargs)
... 		
>>> var = "varA"
>>> obj = struct(**{str(var): "Hello"})
>>> print obj.varA
Hello


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list