【问题标题】:Pass method as a parameter on python在python上将方法作为参数传递
【发布时间】:2018-11-28 23:23:46
【问题描述】:

我可以在 python 上将方法作为参数传递吗? 我想做一些事情,例如,如果有任何东西是具有 foo 方法的对象的实例:

def access_to(class=anything, method="foo"): return class.method

(请注意,Anything 实例显然没有属性“方法”,并且会得到一个 AttributeError)。

【问题讨论】:

  • 我不想调用一个函数作为类对象的方法,我想做的函数在那个之外。

标签: python class methods


【解决方案1】:

如果要从字符串参数中获取方法,请使用 getattr。

class A:
    def foo(self):
        print("foo")

def access_to(c, method="foo"):
     return getattr(c, method)

a = A()
b = 5
access_to(a)()
access_to(b)()

它为 a 打印 foo,然后为 b 引发错误

我不得不说,我建议不要滥用此类功能,除非出于某些特定原因必须这样做。

【讨论】:

  • 优秀。谢谢你! (ps:这是一个非常特殊的情况,我处理过大的命名方法(我没有构建那个)并且我调用一个使用这些方法的函数太多时间。谢谢你)
【解决方案2】:

您当然可以将方法作为参数传递给 Python 中的函数。在下面的示例中,我创建了一个类 (MyClass),它有两个方法:isOddfilterArray。我还在MyClass 之外创建了一个isEven 函数。 filterArray 接受两个参数 - 一个数组和一个返回 TrueFalse 的函数 - 并使用作为参数传递的方法来过滤数组。

此外,您可以将 lambda 函数作为参数传递,这就像动态创建函数一样,无需编写函数声明。

def isEven(num):
    return num % 2 == 0

class MyClass:

    def isOdd(self, num):
        return not isEven(num)

    def filterArray(self, arr, method):
        return [item for item in arr if method(item)]

myArr = list(range(10))  # [0, 1, 2, ... 9]

myClass = MyClass()

print(myClass.filterArray(myArr, isEven))
print(myClass.filterArray(myArr, myClass.isOdd))
print(myClass.filterArray(myArr, lambda x: x % 3 == 0))

输出:

[0, 2, 4, 6, 8]
[1, 3, 5, 7, 9]
[0, 3, 6, 9]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-18
    • 2010-10-16
    • 2010-11-16
    • 2013-08-18
    • 2018-09-09
    • 2019-02-22
    相关资源
    最近更新 更多