Home > OS >  Passing active method as argument in another method python
Passing active method as argument in another method python

Time:11-12

I have seen various questions that kind of touch one this, but never one where the method being passed as an argument is actively used on self. Here's a MWE (or more accurately a MNWE):

class Object:
    def __init__(self, number1, number2):
        self.value1 = number1
        self.value2 = number2
    
    def method1(self):
        return self.value1
    
    def method2(self):
        return self.value2
    
    def super_method(self, method):
        return 2 * self.method()


example = Object(4, 6)
example.super_method(method1)

CodePudding user response:

The super_method just receives a method and call it, and you need to pass the object's method

class Object:
    # ...
    def super_method(self, method):
        return 2 * method()

example = Object(4, 6)
print(example.super_method(example.method1))  # 8
print(example.super_method(example.method2))  # 12

If you want to pass the method without the example reference it would be

class Object:
    # ...
    def super_method(self, method):
        return 2 * method(self)

example = Object(4, 6)
print(example.super_method(Object.method1))  # 8
print(example.super_method(Object.method2))  # 12
  • Related