Reputation: 1892
I have a class A
with a member function a
and a parameter p
with a default value. I want this default value to be the member variable of the class.
class A:
def a(self, p = self.b):
print p
However it crashed with the information:
<ipython-input-2-a0639d7525d3> in A()
1 class A:
----> 2 def a(self, p = self.b):
3 print p
4
NameError: name 'self' is not defined
I want to know whether I can pass a member variable as a default parameter to the member function?
Upvotes: 1
Views: 627
Reputation: 474131
One option would be to set the default p
value as None
and check its value in the method itself:
class A:
def __init__(self, b):
self.b = b
def a(self, p=None):
if p is None:
p = self.b
print(p)
Demo:
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
Upvotes: 3