0

I have several variables like:

class X(object):
    ...

class XY(X):
    ...

class XZ(X):
    ...

class XA(X):
    ...

y=XY()
z=[XZ(i) for i in range(1,10)]
a=[XA(i) for i in range(1,10)]

I would like to have a listlike view(including iteration and length) of the different variable y and the variables inside z and a.

this is for the sake of convenience w/out any worries about performance. I could just do

view = [self.y] + self.z + self.a

each time but that seems to be breaking the DRY principle.

Edit: to clarify that this isn't about taking the instance variables of a class. I just want a view class, probably implementing a list like interface that forwards to other variables. Or would it be better to make a closure that returns a view list when you call it(since I don't care about performance). Which is simpler/more pythonic/a better idea? How would I implement a list like forwarding class?., ect.

Roman A. Taycher
  • 18,619
  • 19
  • 86
  • 141
  • Do you mean [`C.__dict__`](http://stackoverflow.com/a/62680/78845)? – johnsyweb Dec 20 '11 at 08:56
  • what do you need exactly ? a list of the members of your C object ? or a list of all the instances created ? – Cédric Julien Dec 20 '11 at 08:56
  • Could you clarify on your meaning of "listlike"? The example implies that a list variable, `self.view = [self.y, self.z, self.a]` would be appropriate, and that `class C` would just need to return `self.view` for `__repr__`, `__str__`, or `__unicode__`. – Edwin Dec 20 '11 at 08:57
  • z and a are lists thats why its view = [self.y] + self.z + self.a not self.view = [self.y, self.z, self.a] – Roman A. Taycher Dec 20 '11 at 08:58
  • but if z or a change then it won't have the right view. – Roman A. Taycher Dec 20 '11 at 09:09

2 Answers2

2

If I understand correctly you want to "chain" the iterators of self.z and self.a and add self.y to that. Perhaps this does what you want:

import itertools
itertools.chain(self.a, self.z, [self.y])

The cleanest would probably be to implement it like this:

class C(object):
    def __init__(self, y, z, a):
        # ...

    def __iter__(self):
        return itertools.chain(self.a, self.z, [self.y])
orlp
  • 112,504
  • 36
  • 218
  • 315
0

class X:

def __init__ (self, x, y, z):
    self.x = x
    self.y = y
    self.z = z

x = X(1,2,3) print x.dict

Nickle
  • 367
  • 3
  • 5