3

My python code has a class from which instantiates objects representing countries. The class has a constructor.

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

Is there a way to make this code more concise? Here is the pseudocode for what I am seeking.

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

Thank you.

dangerChihuahua007
  • 20,299
  • 35
  • 117
  • 206
  • 3
    A one-line solution only saves you four lines, but will probably make it harder to understand as well. – Hunter McMillen Feb 26 '12 at 01:20
  • 2
    See [this question](http://stackoverflow.com/questions/1389180/python-automatically-initialize-instance-variables) for several approaches, but I don't really recommend going down this road. If you have so many initializing arguments that you think it's not concise enough you probably have too many. – DSM Feb 26 '12 at 01:21

1 Answers1

3

You can do this in one line, but it will only make the code more difficult to read and follow. Here is how you would do it.

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)
jordanm
  • 33,009
  • 7
  • 61
  • 76