Python member variable as parameter
<p>I have a class A with a member function a. I have a parameter p with default value. I want this default value to be the member variable of the class.</p>

<pre><code>class A:
   def a(self, p = self.b):
       print p
</code></pre>

<p>However it crashed with the information:</p>

<pre><code>&lt;ipython-input-2-a0639d7525d3&gt; in A()
      1 class A:
----&gt; 2     def a(self, p = self.b):
      3         print p
      4

NameError: name 'self' is not defined
</code></pre>

<p>I want to know whether I can pass a member variable as a default parameter to the member function?</p>

<p>One option would be to set the default <code>p</code> value as <code>None</code> and check its value in the method itself:</p>

<pre><code>class A:
    def __init__(self, b):
        self.b = b

    def a(self, p=None):
        if p is None:
            p = self.b
        print(p)
</code></pre>

<p>Demo:</p>

<pre><code>In [1]: class A:
    ...:     def __init__(self, b):
    ...:         self.b = b
    ...: 
    ...:     def a(self, p=None):
    ...:         if p is None:
    ...:             p = self.b
    ...:         print(p)
    ...:         

In [2]: a = A(10)

In [3]: a.a()
10

In [4]: a.a(12)
12
</code></pre>

python function class variables default-value