使用Python类任务并遇到问题

问题描述 投票:-2回答:1

City类具有以下属性:名称,国家(城市所在的位置),海拔(以米为单位),

和人口(根据最近的统计数字,大约)。填写max_elevation_city函数的空白

比较三个已定义的实例时,返回城市及其国家的名称(用逗号分隔)

对于指定的最小人口。例如,为最小一百万人口调用该函数:

max_elevation_city(1000000)应该返回“保加利亚索非亚”。

    # define a basic city class
class City:
    name = ""
    country = ""
    elevation = 0 
    population = 0

# create a new instance of the City class and
# define each attribute
city1 = City()
city1.name = "Cusco"
city1.country = "Peru"
city1.elevation = 3399
city1.population = 358052

# create a new instance of the City class and
# define each attribute
city2 = City()
city2.name = "Sofia"
city2.country = "Bulgaria"
city2.elevation = 2290
city2.population = 1241675

# create a new instance of the City class and
# define each attribute
city3 = City()
city3.name = "Seoul"
city3.country = "South Korea"
city3.elevation = 38
city3.population = 9733509

def max_elevation_city(min_population):
    # Initialize the variable that will hold 
# the information of the city with 
# the highest elevation 
    return_city = City()

    # Evaluate the 1st instance to meet the requirements:
    # does city #1 have at least min_population and
    # is its elevation the highest evaluated so far?
    if ___
        return_city = ___
    # Evaluate the 2nd instance to meet the requirements:
    # does city #2 have at least min_population and
    # is its elevation the highest evaluated so far?
    if ___
        return_city = ___
    # Evaluate the 3rd instance to meet the requirements:
    # does city #3 have at least min_population and
    # is its elevation the highest evaluated so far?
    if ___
        return_city = ___

    #Format the return string
    if return_city.name:
        return ___
    else:
        return ""

print(max_elevation_city(100000)) # Should print "Cusco, Peru"
print(max_elevation_city(1000000)) # Should print "Sofia, Bulgaria"
print(max_elevation_city(10000000)) # Should print ""
python class instance
1个回答
0
投票

该课程设置不正确。这些是类变量,每个类实例都相同。您需要实例变量,它对于每个实例都是独立的。 here is a link to learn more

修复

class City:
    def __init__(self, name, country,elevation, population)
        self.name = name
        self.country = country
        self.elevation = elevation
        self.population = population

然后创建一个新实例:

city1 = City("Cusco","Peru",3399,358052)

您仍然可以通过执行操作来获取属性

print(city1.name) # prints "Cusco"
© www.soinside.com 2019 - 2024. All rights reserved.