variable variables
Jean-Michel Pichavant
jeanmichel at sequans.com
Fri Jun 18 10:01:02 EDT 2010
someone wrote:
> On Jun 18, 12:49 pm, James Mills <prolo... at shortcircuit.net.au> wrote:
>
>> On Fri, Jun 18, 2010 at 8:31 PM, someone <petshm... at googlemail.com> wrote:
>>
>>> I was looking for a "short way" to do it because I have a lot
>>> "some_object.attr.attr or some_object.other_attr.attr" in code. it
>>> looks like I cannot replace attr with just other variable and must
>>> type some_object.other_attr.attr or your solution which is however
>>> longer to type :)
>>>
>> It would actually help to see some code.
>>
>>
>
> 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
>
>
>> --James
>>
>
>
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
> I come from A
print fb.bar
> I come from B
fa.bar = 'hello world'
print some_object.A.bar
> hello world
JM
More information about the Python-list
mailing list