Python access to default parameters at init time
<p>The first part of my question is how can i access to the pre-set default parameters of a class to use their value as other arguments? What i want to do is something like this:</p>

<pre><code>class C:

    def __init__(self, size_hint = (0, 0), **kwargs):
        self.size_hint = size_hint
</code></pre>

<p>and then making an instance:</p>

<pre><code>&gt;&gt;&gt; c=C(x = self.size_hint)
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
NameError: name 'self' is not defined
</code></pre>

<p>but at initialization time <code>self</code> and <code>C</code> are also not known.</p>

<p>The second question is in the class definition above how can i set the key, values in the <code>kwargs</code> dictionary as instance attributes?
I know this doesn't work, but what i mean is something like:</p>

<pre><code>for k, v in kwargs.items():
    self.k = v
</code></pre>

<p>Here's the answer to your first question (use <a href="https://docs.python.org/3/library/inspect.html#inspect.signature" rel="nofollow"><code>inspect.signature</code></a>):</p>

<pre><code>import inspect

class C:
    def __init__(self, size_hint = (0, 0), **kwargs):
        self.size_hint = size_hint


assert inspect.signature(C.__init__).parameters['size_hint'].default == (0, 0)
</code></pre>

<p>There's an easier way to get default parameter values, but it doesn't allow you to get them by parameter name if you don't use keyword-only parameters:</p>

<pre><code>assert C.__init__.__defaults__ == ((0, 0),)
</code></pre>

<p>And the answer to the second question:</p>

<pre><code>for k, v in kwargs.items():
    setattr(self, k, v)
</code></pre>

python class python-3.x kwargs