looking for way to include many times some .py code from anotherpython code
Diez B. Roggisch
deetsNOSPAM at web.de
Tue Mar 8 08:28:05 EST 2005
> 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
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,
--
Regards,
Diez B. Roggisch
More information about the Python-list
mailing list