简体   繁体   English

类型 Object '...' 没有属性名称 '...'

[英]Type Object '… ' has no attribute name '… '

I keep on getting the no attribute error in python.我不断收到 python 中的无属性错误。 I want to make a class for cities to put into a program I am writing (Im trying to learn python on the side while working).我想为城市制作一个 class 以放入我正在编写的程序中(我正在尝试在工作时学习 python)。 I basically want to be able to put data into a class for cities and use that in another place.我基本上希望能够将数据放入城市的 class 并在其他地方使用。 I guess, I would need to know how to access attributes from a class.我想,我需要知道如何从 class 访问属性。 Im probably doing a bunch wrong so any feedback would be helpful我可能做错了很多,所以任何反馈都会有所帮助

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)

You are getting confused because you have a variable that has the same name as your class, City .您会感到困惑,因为您有一个与 class, City同名的变量。 To avoid this, use lower-case names for variables.为避免这种情况,请为变量使用小写名称。 Once you change this, you get a different error:一旦你改变了这个,你会得到一个不同的错误:

NameError: name 'city' is not defined NameError:名称“城市”未定义

The reason is that you are trying to print the name of a variable which is defined inside a function , but the print statement is outside the function.原因是您试图打印在function中定义的变量的名称,但print语句在 function之外 To fix this, put your last print statement inside the function city_Compare , and call that function (which you never do).要解决此问题,请将您的最后一条print语句放入 function city_Compare中,然后调用 function(您永远不会这样做)。

Or change the function to return an object instead of printing it:或者更改 function 以return object 而不是打印它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM