简体   繁体   English

在Python中将方法传递给函数

[英]Passing method to a function in Python

I'm trying to pass a method, specifically a method of the string class, to a function which will run it. 我试图将一种方法,特别是字符串类的方法传递给将运行它的函数。 My code looks something like: 我的代码如下所示:

def foo (list):
    for in_str in list[0]:
        print(in_str.list[1]())

# format of list
list = [
    [["Hello world!", "helloworld"], str.isalpha]
]

The desired operation of the function would be to invoke the isalpha method on the string in_str then print the result. 该函数所需的操作是在字符串in_str上调用isalpha方法,然后输出结果。 This doesn't work because in_str obviously doesn't have the attribute list, but I want to know how to make list[1] reference the method. 这不起作用,因为in_str显然没有属性列表,但是我想知道如何使list [1]引用该方法。

Any suggestions? 有什么建议么?

Thanks! 谢谢!

def foo (l):
    for in_str in l[0]:
        print(l[1](in_str))

# format of list
l = [["Hello world!", "helloworld"], str.isalpha]
print(foo(l))

You need to pass a string to str.isalpha , also you have an extra pair of brackets in the list. 您需要将字符串传递给str.isalpha ,而且列表中还有一对括号。

In [2]: foo(l)
False
True

If you just want to pass a function then pass it as a parameter and just pass a list of strings: 如果您只想传递一个函数,则将其作为参数传递,然后传递一个字符串列表:

def foo(l, func):
    for in_str in l[0]:
       print(func(in_str))


l = ["Hello world!", "helloworld"]

print(foo(l,str.isalpha))

A nicer way may be to use map to map the func to each string: 一个更好的办法可能是使用map映射FUNC键,每个字符串:

def foo(l,func):
    return  map(func,l) # list(map(...) python 3

print(foo(l,str.isalpha))

Either you call the function isalpha with a string as an argument: 您可以使用字符串作为参数调用函数isalpha

str.isalpha('Hello World!")

or as an object oriented approach: 或作为一种面向对象的方法:

'Hello World'.isalpha()

In your case we also need to correct some indices. 在您的情况下,我们还需要更正一些索引。 I also changed the variable name list because it shadows the built-in list function. 我还更改了变量名称list因为它遮盖了内置列表功能。

def foo(anestedlist):
    for a_str in anestedlist[0][0]:
        print(anestedlist[0][1](a_str))

# format of list
anestedlist = [[["Hello world!", "helloworld"], str.isalpha]]

and

foo(anestedlist)

prints 版画

False
True

The important part here is 这里重要的是

print(anestedlist[0][1](a_str))

which translates to str.isalpha(a_str) , ie passing a string as an argument. 转换为str.isalpha(a_str) ,即传递一个字符串作为参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM