[Tutor] Getting class method variable values

Reggie Dugard reggie@merfinllc.com
Fri Jun 13 21:42:01 2003


gyro,

What about making prop_list a class variable and preceding each method
definition with a call to extend that list.  Here is an example of my
suggestion:

class C(object):
    prop_list = []
    def __init__(self):
        # need a list combining all properties in all methods
        # basically extending all v's together
        # should be ['prop_a','prop_c','prop_f','prop_z']         
        self.all_props = dict(zip(self.prop_list,
                                  [None]*len(self.prop_list)))

    prop_list.extend(['prop_a','prop_c'])
    def c_1(self):
        #calculate values for property a and c
        self.all_props['prop_a'] = 'val_a'
        self.all_props['prop_c'] = 'val_c'
        return self.all_props

    prop_list.extend(['prop_f','prop_z'])
    def c_2(self):
        #calculate values for property f and z
        self.all_props['prop_f'] = 'val_f' 
        self.all_props['prop_z'] = 'val_z' 
        return self.all_props

>>> myC = C()
>>> myC.c_2()
{'prop_f': 'val_f', 'prop_a': None, 'prop_z': 'val_z', 'prop_c': None}
>>> 

HTH,

On Fri, 2003-06-13 at 17:46, gyro funch wrote:
>  
> What I am trying to do is the following:
> I have a class in which I have many methods, each of which computes the value corresponding to one or more properties. Each method contains a list of the property names for which values are calculated (the name of the list is the same for all methods). 
> 
> What I want to do is to be able to return to the user a dictionary with all of the properties (for all methods) as keys and the values as the computed values (or None if they haven't been calculated). 
> 
> 
> 
> For example:
> 
> class C(object):
> 
>     def __init__(self):
> 
>         # need a list combining all properties in all methods
>         # basically extending all v's together
>         # should be ['prop_a','prop_c','prop_f','prop_z']         
>         prop_list = ?
> 
>         self.all_props = dict(zip(prop_list,None*len(prop_list))
> 
>     def c_1(self):
>         v = ['prop_a','prop_c']
>         calculate values for property a and c
>         self.all_props['prop_a'] = val_a 
>         self.all_props['prop_c'] = val_c 
>         return self.all_props
> 
>     def c_2(self):
>         v = ['prop_f','prop_z']
>         calculate values for property f and g
>         self.all_props['prop_f'] = val_f 
>         self.all_props['prop_z'] = val_z 
>         return self.all_props
> 
> 
> >>> myC = C()
> >>> myC.c2()
> {'prop_a':None, 'prop_c':None, 'prop_f':val_f, 'prop_z':val_z}
> 
> 
> One of my objectives is to be able to add new methods with new property lists to the class and not have to update some master dictionary in the init method. That is why I thought that introspection might make sense.

-- 
Reggie