someone said:
here it is, In Foo I'd like to have instead of A self.type and the
same in class B
from some_module import some_object
class Foo:
def __init__(self):
self.type = 'A'
def printAttr(self):
some_object.A.B
some_object.A.C
some_object.A.D
some_object.A.E
some_object.A.F
some_object.A.G
class Bar:
def __init__(self):
self.type = 'B'
def printAttr(self):
some_object.B.B
some_object.B.C
some_object.B.D
some_object.B.E
some_object.B.F
some_object.B.G
Here is a way to to do it. Note that it is quite dangereous 'cause you
may confuse everyone by accessing some_object attributes like a Foo
attributes. Basically, when the attributes is not found in the Foo
namespace, it will use the some_object.A or some_object.B namespace instead.
some_object = Bar()
some_object.A = Bar()
some_object.B = Bar()
some_object.A.bar = 'I come from A'
some_object.B.bar = 'I come from B'
class Foo(object):
def __init__(self, _type):
self.type = _type
def __getattribute__(self, name):
try:
return object.__getattribute__(self, name)
except AttributeError:
return getattr(getattr(some_object, self.type), name)
def __setattr__(self, name, value):
try:
# first look if self has the attribute, if so set it
if object.__getattribute__(self, name):
return object.__setattr__(self, name, value)
except AttributeError:
# look into some_object
try:
_type = object.__getattribute__(self, 'type')
if hasattr(getattr(some_object, _type), name):
return setattr(getattr(some_object, _type), name, value)
except AttributeError:
pass
# attribute neither found in self nor in some_object, let's
create it in self
return object.__setattr__(self, name, value)
fa = Foo('A')
fb = Foo('B')
print fa.bar
print fb.bar
fa.bar = 'hello world'
print some_object.A.bar
JM