Ruby Impressions

John Machin sjmachin at lexicon.net
Sat Jan 12 17:16:50 EST 2002


Per Gummedal <p.g at figu.no> wrote in message news:<mailman.1010843537.27964.python-list at python.org>...
> 12.01.2002, 08:42, you wrote:
> 
> > adamspitz at bigfoot.com (Adam Spitz) wrote:
> > | class Person:
> > |     def __init__(self, name, age, gender):
> > |         self.name, self.age, self.gender = name, age, gender
> > |         self.doSomeStuff()
> > |I'd like to be able to tell Python, "Make me an __init__ method that
> > |takes these three parameters, stores them as attributes, and then does
> > |this other stuff."
> 
> 
> You could use this function:
> 
> import sys
> 
> CO_VARARGS, CO_VARKEYWORDS = 4, 8
> 
> def initParms(obj):
>     f = sys._getframe(1)
>     n = f.f_code.co_argcount
>     # dict is new in 2.2. Do not include first parm (self)
>     args = dict([(vn, f.f_locals[vn]) for vn in f.f_code.co_varnames[1:n]])
>     obj.__dict__.update(args)
>     # skip varargs
>     if f.f_code.co_flags & CO_VARARGS:
>         n += 1
>     # keywords
>     if f.f_code.co_flags & CO_VARKEYWORDS:
>         obj.__dict__.update(f.f_locals[f.f_code.co_varnames[n]])
> 
> 
> class A:
>     def __init__(self, a, b, c, d):
>         initParms(self)
> 
> a1 = A(1,2,3,4)
> 
> 
> Per

The above doesn't work with new classes with __slots__ (because their
instances have no __dict__). The following uses setattr() instead,
with the side benefit of a slight increase in clarity. Also avoids
using "dict()" and "for x in mapping:", so may even work on versions
of Python earlier than 2.2.

def initParms(obj):
    f = sys._getframe(1)
    n = f.f_code.co_argcount
    # Do not include first parm (self)
    for vn in f.f_code.co_varnames[1:n]:
        setattr(obj, vn, f.f_locals[vn])
    # skip varargs
    if f.f_code.co_flags & CO_VARARGS:
        n += 1
    # keywords
    if f.f_code.co_flags & CO_VARKEYWORDS:
        for k, d in f.f_locals[f.f_code.co_varnames[n]].items():
            setattr(obj, k, d)



More information about the Python-list mailing list