0

I'm a newbie trying to learn Python using the QuantEcon.org lectures. While working through OOP III: The Samuelson Accelerator, I noticed that when a class has many attributes, constructors end up looking like this (culled):

class Samuelson():

    def __init__(self,
                     y_0=100,
                     y_1=50,
                     α=1.3,
                     β=0.2,
                     γ=10,
                     n=100,
                     σ=0,
                     g=0,
                     g_t=0,
                     duration=None):

            self.y_0, self.y_1, self.α, self.β = y_0, y_1, α, β
            self.n, self.g, self.g_t, self.duration = n, g, g_t, duration
            self.γ, self.σ = γ, σ
            self.ρ1 = α + β
            self.ρ2 = -β
            self.roots = np.roots([1, -self.ρ1, -self.ρ2])

As you can see, there's quite a bit of code that simply copies the constructor's arguments to the new object's attributes (self.y_0 = y_0, etc; the first three lines of the constructor).

Repeating what is essentially the same boilerplate code for each argument / attribute strikes as as cumbersome (and somewhat error-prone), especially when a constructor takes (significantly) more arguments than this one does.

My question, therefore: is there a more elegant, "Pythonic" way of doing this?

chsk
  • 113
  • 6
  • Maybe combination of *args, **kwargs and getattr would work. But it kind of is too complicated, but that would be more efficient way I believe. Like you can pass the argument name as the key which has to be initialized with other arguments as key and then use getattr to initialize them. – Amit Amola Jan 01 '19 at 14:22
  • 1
    Have a look at the new [`dataclasses`](https://docs.python.org/3/library/dataclasses.html) (Python 3.7+). – Graipher Jan 01 '19 at 15:58

0 Answers0