Python 键入对象'';没有属性名'';

Python 键入对象'';没有属性名'';,python,class,object,Python,Class,Object,我一直在python中遇到无属性错误。我想为城市创建一个类,将其放入我正在编写的程序中(我试图在工作的同时学习python)。我基本上希望能够将数据放入城市的一个类中,并在另一个地方使用它。我想,我需要知道如何从类访问属性。我可能做错了很多,所以任何反馈都会很有帮助 class City: def __init__(self, name, country, re_growth10): self.name = name #name of the city

我一直在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
。要避免这种情况,请对变量使用小写名称。更改此选项后,会出现不同的错误:

名称错误:未定义名称“城市”

原因是您试图打印函数内部定义的变量的名称,但
print
语句在函数外部。要解决此问题,请将最后一条
print
语句放在函数
city\u Compare
中,并调用该函数(您从未这样做)

或者将函数更改为“返回对象”(而不是打印对象):

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

City.name
是类上的方法,而不是类的实例。试试多伦多。名字。在
city\u比较
以小写字母命名变量时,我也会小心,因此
用于city in cities
而不是
用于city in cities
。看起来像是find\u city中的打字错误:
return cty
->
return city