我正在尝试使用 python 和文本库创建一个具有面向对象设计的天气应用程序。我设置了一个输入小部件,供用户输入位置,例如城市、州和/或国家/地区。然后,我计划访问此输入,以便我可以使用它来检索该位置的天气数据。但是,我似乎无法以我想要的方式访问输入。这是我的代码:
from textual.app import App, ComposeResult
from textual.widgets import Static, Input
class Location:
def __init__(self, search_input: str) -> None:
"""
Initialize the search_input variable.
"""
self.__search_input = search_input
@property
def search_input(self) -> str:
"""
Get the search_input property.
"""
return self.__search_input
@search_input.setter
def search_input(self, newSearchInput: str) -> None:
"""
Set the value of the search_input.
"""
self.__search_input = newSearchInput
def getLocation(search_input) -> list[str]:
"""
Function to define the location.
"""
if search_input != "":
LOCATION = str(search_input)
city = LOCATION
state = ""
country = ""
if len(LOCATION) >= 2:
state = LOCATION[1]
if len (LOCATION) == 3:
country = LOCATION[2]
else:
city = "Test"
state = ""
country = ""
if state == "" and country == "":
LOCATION = [city]
elif state != "" and country == "":
LOCATION = [city, ", ", state]
elif state == "" and country != "":
LOCATION = [city, ", ", "", "", country]
elif state != "" and country != "":
LOCATION = [city, ", ", state, ", ", country]
return LOCATION
class WeatherApp(App):
"""
The main class for the weather app.
"""
def compose(self) -> ComposeResult:
"""
Compose the app.
"""
input = Input(value="",placeholder="Enter a location...")
yield input
location = Location(Input.value)
LOCATION = location.getLocation()
output = Static(LOCATION[0])
yield output
if __name__ == "__main__":
"""
Execute the app.
"""
app = WeatherApp()
app.run()
根据当前代码的设置方式,我预计输出为“测试”。这是因为我将“Input.value”(我认为是输入字符串的值)传递到“getLocation”函数中。然后,因为本例中的 search_input 值将是一个空字符串,所以我认为它将城市的值设置为“Test”,因此导致“LOCATION”的值成为包含字符串的单索引列表“Test”,最终会导致输出值为“Test”。但是,输出的值是“<main.Location object at 0x7f6c2716db10>”。
如何修改我的代码以便可以正确访问输入字符串的值?
分解:
LOCATION = location.getLocation()
output = Static(LOCATION[0])
yield output
这是您获得写入输出的地方,
output
是包裹在LOCATION
中的Static()
(无论此时是什么)的第一个元素。
LOCATION
是.getLocation()
的返回值,但问题是.getLocation
是这样定义的:
class Location:
...
def getLocation(search_input) -> list[str]:
...
由于您将其定义为类定义中的函数,因此它是该类的方法,并且期望第一个参数为
self
。您可以以不同的方式命名它(这就是 search_input
的意思),但它仍然会被分配对象实例本身。
因此,当
.getLocation()
启动时,search_input
是 main.Location
的实例。
您可以将
self,
添加到方法参数列表的开头,但请注意,您实际上并未将任何搜索输入传递给 .getLocation()
,因此这将导致下一个错误。您期望输入如何在通话中结束?
另一个注意事项:您的命名非常有创意,而忽略了许多最佳实践和风格指南,这些最佳实践和风格指南使您的代码更难以阅读,并导致编辑器和 IDE(正确地)生成警告。不要将常规变量命名为全部大写,例如
LOCATION
(除非您打算将它们设置为全局变量,即使这样也是可疑的)。不要使用双下划线,除非您需要像对 .__search_input
那样进行名称修改。不要将蛇形大小写 (search_input
) 与驼峰大小写 getLocation
混合使用 - 蛇形大小写是 Python 的默认大小写,如果您有非常充分的理由偏离它(例如与现有代码库的兼容性),请一致地做出选择,或者你的代码变得几乎不可读并且很难维护。
根据您使用的编辑器或 IDE,它应该指出将
self
重命名为 search_input
的问题,但您可能没有注意到是否到处都有样式和语法警告,这是学习遵循的另一个原因PEP8.