Robert
Robert

Reputation: 129

Python nested Classes - returning multiple values

I'm fairly new to classes in python, so please be gentle. My script is a tad more complicated than this, but this is essentially what it boils down to:

class primary_state:
    def __init__(self,x,y,z):
        self.x = x
        self.y = y
        self.z = z
        self.substates=[]

    def add_substate(self,i,j,k):
        self.substates.append(self.substate(i,j,k))

    class substate:
        def __init__(self,i,j,k):
            self.i = i
            self.j = j
            self.k = k

state = primary_state(1,2,3)
state.add_substate(4,5,6)
state.add_substate(7,8,9)

Now my question is: is it possible to return an array of values from each object? So for example I'd like to do:

state.substates[:].i

and have it return the values of 4 and 7, but alas substates is a list so it can't handle it. There also must be a more efficient way to do this but I haven't quite figured that out yet. Any advice/thoughts would be greatly appreciated! Thanks.

Upvotes: 1

Views: 142

Answers (3)

theodox
theodox

Reputation: 12208

list comprehensions are the way to do it as the other answers point out.

If the only job of the primary state class is to hold subclasses, you can make your class behave like an iterable. In the example you give this is mostly syntactic sugar, but it can be useful. Complete instructions on how to do it are here but it's pretty simple:

class PrimaryState(object):  #always use "new style" classes! its 2013!
    def __init__(self,x,y,z):
        self.x = x
        self.y = y
        self.z = z
        self.substates=[]

    def __len__(self):
       return len(self.substates)

    def __getitem__(self, index):
       return self.substates[index]

    def __iter__(self):
       for sub in substates: yield sub

    def __contains__(self, item):
        return item in self.substates

        def add(self, item): 
            self.substates.append(item)

This way you can do:

 primary = PrimaryState(1,2,3)
 primary.add(SubState(4,5,6))
 primary.add(SubState(7,8,9))

 for item in primary:
     print item

 # Substate 4,5,6
 # Substate 7,8,9

PS: Check out PEP-8, the standard python style guide for naming classes and so on. And use new style classes (inheriting from object). Down the road it's important!

Upvotes: 0

kriomant
kriomant

Reputation: 2326

You can get the list of substates by calling:

[substate.i for substate in self.substates]

Upvotes: 0

user2357112
user2357112

Reputation: 281381

Use a list comprehension.

[sub.i for sub in state.substates]

This is roughly equivalent to the following:

x = []
for sub in state.substates:
    x.append(sub.i)

except shorter, and it's an expression that you can embed in other expressions instead of a series of statements.

Upvotes: 4

Related Questions