Export variables

M

msolem

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.

Thanks,
Mike
 
D

Diez B. Roggisch

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())
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,990
Messages
2,570,211
Members
46,796
Latest member
SteveBreed

Latest Threads

Top