How can you refer to a class method in the 'header' of another class method as a default variable?

Viewed 63

I am working on a class, where I would like to achieve something that broadly looks like this:

class Class:
   def __init__(self, x = 4):
      self.x = x

   def Square(self):
      return self.x ** 2

   def MathsOperator(self, operator = self.Square):
      return operator()

Note that the above class I've only just created for the purpose of illustrating what I would like to achieve. Essentially, I would like to have a method that takes in other methods, but has a default method set from within the same class. So here, self.MathsOperator is a method that can take any method by using the parameter operator. However, by default it is set to the method self.Square.

I have tried replacing self.Square with Class.Square, but this does not work either.

Is this possible in Python?

1 Answers

self is only defined with a method's scope, so as you can see you can't use it in the default arguments clause. You could pass Square (without the self), but note you'll need to pass self when calling it:

def MathsOperator(self, operator = Square):
    return operator(self)
Related