了解类内的 python 变量范围
我试图在类中定义一个变量,然后可以从该类中的函数访问/更改该变量。
例如:
class MyFunctions():
def __init__( self):
self.listOfItems = []
def displayList( self):
"""Prints all items in listOfItems)"""
for item in self.listOfItems:
print item
def addToList(self):
"""Updates all mlb scores, and places results in a variable."""
self.listOfItems.append("test")
f = MyFunctions()
f.addToList
f.displayList
这应该为我输出列表中的所有项目,但它什么也不显示。我假设发生这种情况是因为我没有正确设置变量的范围。我希望能够从 MyFuctions 中的所有函数中访问和更改 listOfItems。
我已经尝试解决这个问题几个小时了,所以任何帮助将不胜感激。
I am trying to define a variable in a class that then can be accessed/changed from functions within that class.
For example:
class MyFunctions():
def __init__( self):
self.listOfItems = []
def displayList( self):
"""Prints all items in listOfItems)"""
for item in self.listOfItems:
print item
def addToList(self):
"""Updates all mlb scores, and places results in a variable."""
self.listOfItems.append("test")
f = MyFunctions()
f.addToList
f.displayList
This should output all of the items in the list for me, but instead it displays nothing. I am assuming this is occuring because I did not setup the scope of the variables correctly. I want to be able to access and change listOfItems from within all of the functions in MyFuctions.
I have been trying to figure this out for a few hours now, so any help would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
f.addToList
和f.displayList
不会分别调用addToList
和displayList
方法。它们只是对方法本身进行求值(在本例中绑定到对象f
)。添加括号来调用方法,就像程序的更正版本中一样:这与 Ruby 不同,Ruby 不需要括号来调用方法(除了在某些情况下消除歧义)。
将以下内容添加到程序末尾是有启发性的:
这将输出类似以下内容:
证明这是方法引用而不是方法调用。
f.addToList
andf.displayList
do not invoke the methodsaddToList
anddisplayList
respectively. They simply evaluate to the method (bound to the objectf
in this case) themselves. Add parentheses to invoke the methods as in the corrected version of the program:This is in contrast to Ruby which does not require parentheses for method invocation (except to eliminate ambiguity in certain cases).
It is instructive to add the following to the end of your program:
This will output something like the following:
demonstrating that this is a method reference and not a method invocation.