如何使用Python将类内声明为局部变量的字典的值获取

如何使用Python将类内声明为局部变量的字典的值获取,python,list,class,function,dictionary,Python,List,Class,Function,Dictionary,我想知道如何在类中获取声明为局部变量的字典的值?看看下面我的消息来源。 注意:如果我在函数get\u current\u weather中声明这个变量,它就可以正常工作 class Weather(object): weather = { 'January' : 'cold', 'Febrary' : 'cold' } def get_current_weather(self): prin

我想知道如何在类中获取声明为局部变量的字典的值?看看下面我的消息来源。 注意:如果我在函数get\u current\u 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**
回溯(最近一次呼叫最后一次):
文件“game.py”,第27行,在
天气。获取当前天气()
文件“game.py”,第24行,当前天气
打印天气[‘一月’]
**TypeError:“Weather”对象不可下标**

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

def get_current_weather(self):
    print self.weather['January']  # or  Weather.weather['January']
类本身就是名称空间,所以类中的变量成为它的属性:

i、 e
weather
班内实际上是:
weather.weather

例如:

>>> class A:
...     foo = 1
...     bar = 2
...     
>>> A.foo
1
>>> A.bar
2

P.S
weather
不是一个列表,它是一个字典
get\u current\u weather
,如果你想让它成为weather类的一员,它应该缩进。@DavidMarek谢谢。看起来Stackoverflow没有正确粘贴它。