开发者

Output all members from a class defines as list

Hi I've got a class that essentially is a list object holding a bunch of objects. I try to define a method to return all members, but it fails. My code is:

class Stadion:
    def __init__(self,):
        self.__Tribuner=[]

    def setTribuner(self,tribuner):
        self.__Tribuner.append(tribuner)
    def getTribuner(self):
        pass
    def getAntallTribuner(self):
        antall=len(self.__Tribuner)
        return antall
    def addTribune(self,tribune):
        self.__Tribuner.append(tribune)
    def getTribuner(self):
        for tr in self.__Tribuner:
            return tr

Mye problem is the getTr开发者_JAVA百科ibuner method.

/Andy.l


Maybe you want

def getTribuner(self):
    return self.__Tribuner

or

def getTribuner(self):
    for tr in self.__Tribuner:
        yield tr

I would recommend to expose the standard Python sequence interface instead of your custom method names. In your case it would be easiset to just derive Stadion from list.


The first time it hits return tr, it will quit. You either want to return a generator (yield tr) or just return self.__Tribuner.


If you're wanting to iterate through the items, swap return for yield in getTribuner.


Try:

def getTribuner(self):
    return self.__Tribuner

If don't want to return the list at once, you can use a generator, like so:

def getTribuner(self):
    for tr in self.__Tribuner:
        yield tr

# usage it within a loop ...
for tr in instance.getTribuner():
    # process tr

This will return a list with all members in self.__Tribuner.

Sidenote: Concerning getters and setters in python, see this article:

  • http://tomayko.com/writings/getters-setters-fuxors


class Stadion(object):
    def __init__(self, tribuner):
        self.tribuner = tribuner

In your code, replace stadion.GetTribuner() with stadion.tribuner. Replace stadion.SetTribuner(t) with stadion.tribuner = t. To iterate over tribuner, use for x in stadion.tribuner: Now you're programming in Python rather than in Java.


Subclass from UserList.UserList, and all this get's much easier. :) Or directly from list. Or even better do this:

class Stadion:
    def __init__(self,):
        self.tribuner=[]

Done. Thats all you need. You want to add a SitteTribun:

stadion = Stadion()
stadion.tribuner.append(SitteTribute())

Getting all the Tribuner:

stadion.tribuner

Looping over them:

for tribun in stadion.tribuner:
    whatevah()

Counting:

len(stadion.tribuner)

Yes. Python really is that easy. :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜