looking for way to include many times some .py code fromanotherpython code

Steven Bethard steven.bethard at gmail.com
Tue Mar 8 16:47:32 EST 2005


Martin MOKREJŠ wrote:
> Basically, doing in a class method
> def(self, a, b, c):
>    self.a = a
>    self.b = b
>    self.c = c
> sounds stupid. With next instance I'll loose a, b, c, so I have to save
> then to a variable, "self." prefix is generally proposed way. But
> it's not surprising a gets to self.a, right? Actually, I thought about
> the *args tuple and even **kwargs, but I thought this will make the core
> even less readable. Thinking of it now, you'd probably do
> self.__dict__.update(kwargs), right? Hmm, but does it assign to self or 
> not?
> I mean, does it equivalent to `a = 1' or `self.a = 1' ? The latter seem to
> be true, right?

Try it and see:

py> def update1(obj, **kwargs):
...     obj.__dict__.update(kwargs)
...
py> def update2(obj, a, b, c):
...     obj.a, obj.b, obj.c = a, b, c
...
py> class C(object):
...     pass
...
py> c = C()
py> update1(c, a=1, b=2, c=3)
py> c.a, c.b, c.c
(1, 2, 3)
py> c = C()
py> update2(c, a=1, b=2, c=3)
py> c.a, c.b, c.c
(1, 2, 3)
py> c = C()
py> update1(c, 1, 2, 3)
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
TypeError: update1() takes exactly 1 argument (4 given)
py> c = C()
py> update2(c, 1, 2, 3)
py> c.a, c.b, c.c
(1, 2, 3)

Note however that unless you do something like

def update(obj, **kwargs):
     assert list(kwargs) == 'a b c'.split()
     ...

then the update with the **kwargs will take any parameters (not just a, 
b and c).  Don't know if that matters to you.

STeVe



More information about the Python-list mailing list