输出类定义中的所有成员作为列表
你好 我有一个类,本质上是一个包含一堆对象的列表对象。我尝试定义一个方法来返回所有成员,但失败了。 我的代码是:
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
我的问题是 getTribuner 方法。
/安迪.l
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 getTribuner method.
/Andy.l
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
也许你想要
或者
我建议公开标准 Python 序列接口 而不是您的自定义方法名称。在您的情况下,从
list
派生Stadion
会很容易。Maybe you want
or
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
fromlist
.第一次点击
return tr
时,它将退出。您要么想要返回一个生成器 (yield tr
),要么只是返回 self.__Tribuner
。The first time it hits
return tr
, it will quit. You either want to return a generator (yield tr
) or justreturn self.__Tribuner
.如果您想迭代这些项目,请将 getTribuner 中的
return
替换为yield
。If you're wanting to iterate through the items, swap
return
foryield
in getTribuner.尝试:
如果不想立即返回列表,您可以使用 生成器,如下所示:
这将返回一个包含
self.__Tribuner
中所有成员的列表。旁注:关于Python中的getter和setter,请参阅这篇文章:
Try:
If don't want to return the list at once, you can use a generator, like so:
This will return a list with all members in
self.__Tribuner
.Sidenote: Concerning getters and setters in python, see this article:
在您的代码中,将
stadion.GetTribuner()
替换为stadion.tribuner
。将stadion.SetTribuner(t)
替换为stadion.tribuner = t
。要迭代 tribuner,请使用for x in stadion.tribuner:
现在您正在使用 Python 而不是 Java 进行编程。In your code, replace
stadion.GetTribuner()
withstadion.tribuner
. Replacestadion.SetTribuner(t)
withstadion.tribuner = t
. To iterate over tribuner, usefor x in stadion.tribuner:
Now you're programming in Python rather than in Java.来自
UserList.UserList
的子类,这一切变得更加容易。 :) 或者直接从列表中。或者更好地这样做:完成。这就是你所需要的。您想要添加一个 SitteTribun:
获取所有 Tribuner:
循环遍历它们:
计数:
是。 Python 真的就是这么简单。 :-)
Subclass from
UserList.UserList
, and all this get's much easier. :) Or directly from list. Or even better do this:Done. Thats all you need. You want to add a SitteTribun:
Getting all the Tribuner:
Looping over them:
Counting:
Yes. Python really is that easy. :-)