簡體   English   中英

類型 Object '...' 沒有屬性名稱 '...'

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

我不斷收到 python 中的無屬性錯誤。 我想為城市制作一個 class 以放入我正在編寫的程序中(我正在嘗試在工作時學習 python)。 我基本上希望能夠將數據放入城市的 class 並在其他地方使用。 我想,我需要知道如何從 class 訪問屬性。 我可能做錯了很多,所以任何反饋都會有所幫助

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)

您會感到困惑,因為您有一個與 class, City同名的變量。 為避免這種情況,請為變量使用小寫名稱。 一旦你改變了這個,你會得到一個不同的錯誤:

NameError:名稱“城市”未定義

原因是您試圖打印在function中定義的變量的名稱,但print語句在 function之外 要解決此問題,請將您的最后一條print語句放入 function city_Compare中,然后調用 function(您永遠不會這樣做)。

或者更改 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