可以让Python构造函数更简洁吗?

时间:2012-02-26 01:14:34

标签: python

我的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

谢谢。

1 个答案:

答案 0 :(得分:3)

您可以在一行中执行此操作,但这只会使代码更难以阅读和遵循。以下是你将如何做到这一点。

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)