[Tutor] Getting class method variable values

Magnus Lyckå magnus@thinkware.se
Fri Jun 13 17:35:02 2003


At 16:48 2003-06-13 -0400, gyro funch wrote:
>I am trying to have the __init__ method of my class inspect each of the 
>class methods and create a variable based on these values.

It's not clear what 'these values' means, but the code below
suggests that you refer to values of local variables inside each
method. Local variables are just that: Local. They don't exist
outside that scope. They only have a meaning while the method
is executing. In this particular case, you think that you can
predict their values, but if you change c1 to

     def c1(self):
         print v_1
         v_1 = [1,2,3]

you will maybe understand that this is a flawed assumption. If
not, try running the c1 method for an instance of C. v_1 only
has a value when the line "v_1 = [1,2,3]" has been executed,
and only while python is still executing c1. (Unless we delete
v_1 before that.)

What you are doing by defining v_1 and v_2 as locals is to say
that they should be unavailable outside the methods c1 and c2.

Make them class attributes if that's what you want them to be.

>class C(object):
>     def __init__(self):
>         from inspect import getmembers, ismethod
>         self.vvalues = []
>         for name,value in getmembers(self):
>             if ismethod(value):
>                 vnames = value.im_func.func_code.co_names
>                 for vname in vnames:
>                     if vname.startswith('v_'):
>                         vvalue = ? # how do I get this?
>                         self.vvalues.extend(vvalue)
>
>     def c1(self):
>         v_1 = [1,2,3]
>
>     def c2(self):
>         v_2 = [5,6,7]
>
>I would like the following:
> >>> myC = C()
> >>> myC.vvalues
>[1,2,3,5,6,7]
>
>I can get the names of the variables (v_1,v_2), but I can't figure out how 
>to get the value bound to each variable.

Good! :) That's how it must be...

>Any suggestions are appreciated.

As usual when people try to do very obscure things in Python,
we want to know what you *really* want to achieve, and we'll
tell you a more pythonic way of doing it...

You know, a Python could be your best friend, but don't try
to squeeze it into something that it isn't, because Pythons
can squeeze back much harder than you can... ;)

If you just want to make your programs really difficult to
understand, try Perl or C instead. ;) But I guess that's not
really what you are after. I'm really curious...

/Magnus

P.S. c1 and c2 aren't real class methods. See
http://www.python.org/2.2.3/descrintro.html#staticmethods
Real class methods (or static methods) don't solve your problem
though. Local variables are still local variables...


--
Magnus Lycka (It's really Lyckå), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language