Export variables

Diez B. Roggisch deets at nospam.web.de
Tue Apr 21 12:29:53 EDT 2009


msolem at linuxmail.org wrote:

> Hello,
> 
> I want to make a certain subset of public attributes available through
> an interface.
> 
> The client should not need to know the names of the attributes.
> 
> Here is some code with the important parts missing.  Anyone care to
> fill in the missing parts?
> 
> 
> class C:
>     def __init__(self):
>         self.a = 4
>         self.b = 6
>         self.c = 8
>         self._set_vars([self.a, self.b])  # This call might need to be
> done differently
> 
>     def get_vars(self):
>         # add code here...
> 
>     def _set_vars(self, vars):
>         # add code here...
> 
> 
> c = C()
> print c.get_vars()
> c.a = 9
> print c.get_vars()
> 
> 
> This is the desired output
> [4, 6]   # Values of c.a and c.b
> [9, 6]   # Values of c.a and c.b
> 
> The important part is that the change to c.a is reflected in the call
> to get_vars().  get_vars() and _set_vars() might be moved to a base
> class,
> and therefore should not have attribute names hard coded in them.
> 
> I don't have a specific problem that I'm trying to solve.  I would
> just like
> to know how this sort of thing could be done.

I'd do it roughly like this:

class Base(object):

    EXPORTED_VARIABLES = []


    def get_vars(self):
        all_variables = set(sum((getattr(cls, "EXPORTED_VARIABLES", []) for
cls in self.__class__.mro()), []))
        for varname in all_variables:
            yield getattr(self, varname)


class A(Base):

    EXPORTED_VARIABLES = ["a"]

    a = "A!"


class B(Base):

    EXPORTED_VARIABLES = ["b"]

    b = "B!"


class C(A,B):
    pass


a = A()
b = B()
c = C()

print list(a.get_vars())
print list(b.get_vars())
print list(c.get_vars())




More information about the Python-list mailing list