variable variables

someone petshmidt at googlemail.com
Fri Jun 18 08:19:50 EDT 2010


On Jun 18, 2:05 pm, Bruno Desthuilliers <bruno.
42.desthuilli... at websiteburo.invalid> wrote:
> someone a crit :
>
>
>
>
>
> > 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
>
> from some_module import some_object
>
> def print_attributes(obj, *attribs):
>    for attr in attribs:
>      print getattr(obj, attr, None)
>
> class Foo(object):
>    type = 'A'
>
>    def print_attr(self):
>      print_attributes(getattr(someobject, self.type), *"BCDEFG")
>
> class Bar(Foo)
>    type = 'B'
>
> Still has a "code smell" thing to me, but hard to say not knowing the
> real code and context.

sorry, code is not about printing variables rather accessing, it's
just example.



More information about the Python-list mailing list