1

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?

1 Answer 1

3

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

3 Comments

I have several parameters and I don't want to judge them one by one. Can this be wraped into a function? one problem is that if they are warped into a function, the value variable can not be set in a function.
@maple okay, yeah, that does not scale that good. Do you want all the method arguments have the same self.b default value? Thanks.
I want they have different default value and can be set in the funciton.

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.