gpt4 book ai didi

python - 可以使 Python 构造函数更简洁吗?

转载 作者:行者123 更新时间:2023-11-28 16:49:28 26 4
gpt4 key购买 nike

我的 python 代码有一个类,从中实例化代表国家的对象。该类有一个构造函数。

class Country:
def __init__(self, population, literacy, firms, area, populationDensity):
self.population = population
self.literacy = literacy
self.firms = firms
self.area = area
self.populationDensity = populationDensity

有没有办法让这段代码更简洁?这是我正在寻找的伪代码。

class Country:
def __init__(self, population, literacy, firms, area, populationDensity):
# assign object these properties in one line

谢谢。

最佳答案

您可以在一行中完成此操作,但这只会使代码更难阅读和遵循。以下是您的操作方法。

class Country:
def __init__(self, population, literacy, firms, area, populationDensity):
(self.population, self.literacy, self.firms, self.area, self.populationDensity) = (population, literacy, firms, area, populationDensity)

关于python - 可以使 Python 构造函数更简洁吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9449668/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com