我继续在python中获取no属性错误。我想为城市开设一个班级,以放入正在编写的程序中(我正在尝试一边工作一边学习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)
答案 0 :(得分:1)
您会感到困惑,因为您拥有一个与班级City
同名的变量。为避免这种情况,请对变量使用小写名称。更改此设置后,您将收到其他错误:
NameError:名称“ city”未定义
原因是您试图打印在函数内 中定义的变量的名称,但是print
语句在函数外 。要解决此问题,请将最后一个print
语句放在函数city_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")