python - 类型对象“...”没有属性名称“...”
问题描述
我不断收到python中的无属性错误。我想为城市开设一门课程,以将其放入我正在编写的程序中(我正在尝试一边工作一边学习 python)。我基本上希望能够将数据放入城市类中并在其他地方使用。我想,我需要知道如何从一个类中访问属性。我可能做错了很多,所以任何反馈都会有所帮助
class City:
def __init__(self, name, country, re_growth10):
self.name = name #name of the city
self.country = country #country the city is in
self.re_growth10 = re_growth10 #City Real estate price growth over the last 10 years
def city_Info(self):
return '{}, {}, {}'.format(self.name, self.country, self.re_growth10)
Toronto = City("Toronto", "Canada", 0.03) #Instance of CITY
Montreal = City("Montreal", "Canada", 0.015) #Instance of CITY
user_CityName = str(input("What City do you want to buy a house in?")) #user input for city
def city_Compare(user_CityName): #Compare user input to instances of the class
cities = [Toronto, Montreal]
for City in cities:
if City.name == user_CityName:
print(City.name)
else:
print("We Don't have information for this city")
return ""
print(City.name)
解决方案
您会感到困惑,因为您有一个与您的类同名的变量,City
. 为避免这种情况,请为变量使用小写名称。一旦你改变了这个,你会得到一个不同的错误:
NameError:名称“城市”未定义
原因是您试图打印在函数内部定义的变量的名称,但该print
语句位于函数外部。要解决此问题,请将您的最后一条print
语句放在 functioncity_Compare
中,然后调用该函数(您永远不会这样做)。
或者将函数更改为return
对象而不是打印它:
def find_city(name):
cities = [Toronto, Montreal]
for city in cities:
if city.name == name:
return city
return None
city_name = input("What City do you want to buy a house in?")
city = find_city(city_name)
if city is not None:
print(city.name)
else:
print("We Don't have information for this city")
推荐阅读
- sql - 需要帮助了解一些执行计划
- android - Room 中的异步事务
- amazon-web-services - 如何等待通过 cli 创建 ec2 实例?
- php - 如何在 laravel 中访问控制器内的对象属性?
- ceph - Ceph luminous Filestore 到 Bluestore 迁移卡住
- python - 如何制作一个“翻译”字母的程序?
- java - ConcurrentModificationException 房间 Android
- php - 使用 PHP 电子表格 1.2.1 保存图表
- javascript - 在 React-Redux Store 中配置 devToolsExtension 和 applyMiddleware()
- sql - HackerRank 天气观测站 5