0

我想知道如何获取在类中声明为局部变量的字典的值?看看我下面的来源。注意:如果我在函数 get_current_weather 中声明这个变量,它就可以正常工作

class Weather(object):
    weather = {
        'January' : 'cold',
        'Febrary' : 'cold'
        }

    def get_current_weather(self):             
        print weather['January']

weather = Weather()
weather.get_current_weather()

终端错误:

Traceback (most recent call last):
File "game.py", line 27, in <module>
weather.get_current_weather()
File "game.py", line 24, in get_current_weather
print weather['January']
**TypeError: 'Weather' object is not subscriptable**
4

1 回答 1

1

使用self.weather,否则 python 将尝试查找名为的全局变量weather

def get_current_weather(self):
    print self.weather['January']  # or  Weather.weather['January']

类本身就是一个命名空间,因此类中的变量成为它的属性:

weather课内实际上是:Weather.weather

例子:

>>> class A:
...     foo = 1
...     bar = 2
...     
>>> A.foo
1
>>> A.bar
2
于 2013-06-16T20:50:10.377 回答