【问题标题】:Understanding python variable scope within class了解类中的python变量范围
【发布时间】:2011-04-15 07:13:33
【问题描述】:

我正在尝试在一个类中定义一个变量,然后可以从该类中的函数访问/更改该变量。

例如:

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。

我已经尝试了几个小时来解决这个问题,因此我们将不胜感激。

【问题讨论】:

  • 你用什么教程来学习 Python?

标签: python syntax methods call


【解决方案1】:

f.addToListf.displayList 不分别调用方法 addToListdisplayList。他们只是自己评估方法(在这种情况下绑定到对象f)。添加括号以调用程序更正版本中的方法:

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()

这与 Ruby 不同,Ruby 不需要括号来调用方法(除了在某些情况下消除歧义)。

将以下内容添加到程序的末尾是有益的:

print type(f.addToList)

这将输出如下内容:

<type 'instancemethod'>

证明这是一个方法引用而不是一个方法调用。

【讨论】:

  • 感谢您的帮助!我一直在寻找错误的东西。你为我节省了大量时间!
  • FWIW,这就是 Python 的交互模式证明其价值的地方。您可以运行一个脚本并通过运行python -i myscript.py 让它将您放入交互式shell。从那里您可以交互式地修改脚本的环境。例如,如果您以交互方式调用f.addToList,您会看到它是一个绑定方法。 :)
猜你喜欢
  • 2013-04-11
  • 1970-01-01
  • 1970-01-01
  • 2015-05-02
  • 1970-01-01
  • 2022-01-11
相关资源
最近更新 更多