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.

2
  • 3
    A one-line solution only saves you four lines, but will probably make it harder to understand as well. Commented Feb 26, 2012 at 1:20
  • 2
    See this question 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. Commented Feb 26, 2012 at 1:21

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

You can drop the parentheses around the two sides of the assignment.
Thanks, that works, but I think I'm still putting the code in multiple lines as you had recommended.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.