将活动方法作为参数传递给另一个方法 python
Passing active method as argument in another method python
我见过各种各样的问题,其中一个涉及到这个问题,但从来没有一个问题是在 self
上积极使用作为参数传递的方法。这是一个 MWE(或更准确地说是一个 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)
super_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
如果你想在没有 example
引用的情况下传递方法,它将是
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
我见过各种各样的问题,其中一个涉及到这个问题,但从来没有一个问题是在 self
上积极使用作为参数传递的方法。这是一个 MWE(或更准确地说是一个 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)
super_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
如果你想在没有 example
引用的情况下传递方法,它将是
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