Well, consider that you haven't actually made any kind of a case for using variables!Diez B. Roggisch wrote:
See my post on Mar 2 about "automating assignment of class variables". I got no answers, maybe I wasn't clear enough ... :(
Seems so - I for example didn't understand it.
I need to define lots of variables. The variable names are often
identical. The problem is that if I put such a code into a function ...
no, I'm not going to pass anything to a function to get it returned back.
I just want to get lots of variables assigned, that all. If I put them
into module, it get's exectued only once unless I do reload. And I'd have
to use: "from some import *", because mainly I'm interrested in assigning
to self: self.x = "blah"
self.y = "uhm"
Okay, I try and guess: From your two posts I infer that you want to set
variables in instances. But you've got lots of these and you don't want to
write code like this:
class Foo: def __init__(self, a, b, .....): self.a = a self.b = b ....
If that is what you want, then this might help you: Put all the values in a
Good guess! ;)
dictionary - like this:
my_vals = {"a": 1, "b" : 2, ....}
There are plenty of other ways to create such a dictionary, but I won't digress on that here.
Now in your class, you pass than dict to your constructor and then simply update the instance's __dict__ so that the keys-value-pairs in my_vals become attributes:
class Foo:
def __init__(self, my_vals): self.__dict__.update(my_vals)
foo = Foo(my_vals)
print foo.a
-> 1
Hope this helps,
Sure. Thanks! Would you prefer exactly for this method over the method posted by Kent Johnson
few minutes ago?
Am I so deperately fighting the language? No-one here on the list needs to set hundreds
variables at once somewhere in their code? I still don't get why:
If the names of these things are dynamic then why would you want to put them in an object's namespace, when you could just as easily include
self.insDict = {}
in your __init__() method and then simply update self.insDict whenever you want.
If you "set hundreds variables", and their names aren't predictable, then presumably you will have to go through similar contortions to access them.
So it is generally simpler just to use a dictionary to hold the values whose names aren't known in advance. Techniques for inserting names into namespaces are known (as you have discovered), but when a beginner wants to know about them it's usually considered a sign of "fighting the language".
So, think about this a while and then tell us exactly *why* it's so important that these values are stored in variables.
"include somefile.py" would be that non-pythonic so that it's not available, but
I have already two choices how to proceed anyway. Thanks. ;)
Now have to figure out how to assign them easily into the XML tree.
martin
You do know there are lots of Python libraries that support XML, right?
regards Steve
-- http://mail.python.org/mailman/listinfo/python-list