使用类的方法来更新类的变量实例是否正确?如果是,我该怎么做?

2024-10-01 02:36:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码

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

其中的变量不会随着真实世界的天气而更新。两个问题,为什么不呢,我想作为一个次要问题,我做得对吗?我的方法应该是使用类中的方法来操作类的实例吗?你知道吗


Tags: jsonclouddata特征wind天气weathertemperature
3条回答

这里有两个基本问题。你知道吗


首先,您混合了类属性——也就是说,由同一类的所有实例共享的变量和普通的实例属性——也就是说,变量是每个实例的一部分。你知道吗

您很少需要任何类属性。但是,始终需要实例属性。因此,首先:

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将自动查找类属性type(this).temperature。如果随后添加名为temperature的实例属性,它将“隐藏”class属性,因此下次执行this.temperature时,将获得实例的值。你知道吗

因此,您可以使用类属性作为实例属性的“默认值”。但你只有知道自己在做什么才应该这么做。(比如说,如果开始使用列表之类的可变值并在方法中对它们进行变异,这会让人非常困惑……)

Two questions, why not, and I guess as more of a sub-question, am I doing this right?

您正在更新getWeather()中的局部变量。你知道吗

您应该改为更新实例变量,这可以通过在变量名称前面加上self来完成,换句话说,替换:

def getWeather(self):
    ...
    cloud = ...

def getWeather(self):
    ...
    self.cloud = ...

你的例子中的缩进破了吗?这些变量应该是天气类的类成员吗?你知道吗

同样,函数是跟踪它们,在本地创建新的,因此不改变其他的。你知道吗

相关问题 更多 >