我有以下代码;
class weather(object):
temperature = 0
humidity = 0
precis = "There is no weather when there plainly should be, please contact an administrator."
cloud = "none"
windDirection = "nnw"
windSpeed = 0
def getWeather(self):
weatherJSON = requests.get('http://www.bom.gov.au/fwo/IDT60901/IDT60901.94970.json')
weatherDoc = json.loads(weatherJSON.text)
temperature = weatherDoc["observations"]["data"][1]["apparent_t"]
humidity = weatherDoc["observations"]["data"][1]["rel_hum"]
windDirection = weatherDoc["observations"]["data"][1]["wind_dir"]
windSpeed = weatherDoc["observations"]["data"][1]["wind_spd_kmh"]
cloud = weatherDoc["observations"]["data"][1]["cloud_type"]
这是具有天气功能的类,并包含更新它们的功能。如果我然后用实例化该类
this = weather()
this.getWeather()
此变量不会随实际天气更新。有两个问题,为什么不呢?我想这只是一个子问题,我是对的吗?我的方法应该是使用类中的方法来操纵该类的实例吗?
您这里有两个基本问题。
首先,您要混合使用类属性(即,由同一类的所有实例共享的变量)和普通实例属性(即,作为每个实例的一部分的变量)。
您很少需要任何东西的类属性。但是,您一直都需要实例属性。因此,从以下内容开始:
class weather(object):
def __init__(self):
self.temperature = 0
self.humidity = 0
self.precis = "There is no weather when there plainly should be, please contact an administrator."
self.cloud = "none"
self.windDirection = "nnw"
self.windSpeed = 0
注意self.temperature
,而不仅仅是temperature
。这就是创建实例属性的方式。这也是您访问或更新之一的方式。
其次,您还要将局部变量(即,函数运行时存在并随后消失的变量)与实例属性混合在一起。但是您已经知道从上面更新实例属性很热。所以:
def getWeather(self):
weatherJSON = requests.get('http://www.bom.gov.au/fwo/IDT60901/IDT60901.94970.json')
weatherDoc = json.loads(weatherJSON.text)
self.temperature = weatherDoc["observations"]["data"][1]["apparent_t"]
self.humidity = weatherDoc["observations"]["data"][1]["rel_hum"]
self.windDirection = weatherDoc["observations"]["data"][1]["wind_dir"]
self.windSpeed = weatherDoc["observations"]["data"][1]["wind_spd_kmh"]
self.cloud = weatherDoc["observations"]["data"][1]["cloud_type"]
self.precis = '???'
(我不确定您要输入什么precis
,但是显然您不想将其保留为“没有天气…”。)
如果您在没有第一个解决方案的情况下进行了第二个修复,则一切似乎都可以正常进行,但只是偶然。当您要求时this.temperature
,如果this
没有命名实例属性temperature
,Python会自动寻找class属性type(this).temperature
。如果然后添加一个名为的实例属性temperature
,它将“遮盖”该类属性,因此下次执行操作时this.temperature
,您将获得实例的值。
因此,您可以将类属性用作实例属性的一种“默认值”。但是,只有知道自己在做什么,才应该这样做。(例如,如果您开始使用可变值(例如列表)并在方法中对其进行变异,那将使您非常困惑。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句