“绑定方法"是什么意思错误是指当我调用函数时? [英] What does "bound method" error mean when I call a function?
问题描述
我正在创建一个单词解析类并且我不断收到一个
I am creating a word parsing class and I keep getting a
bound method Word_Parser.sort_word_list of <__main__.Word_Parser instance at 0x1037dd3b0>
运行时出错:
class Word_Parser:
"""docstring for Word_Parser"""
def __init__(self, sentences):
self.sentences = sentences
def parser(self):
self.word_list = self.sentences.split()
def sort_word_list(self):
self.sorted_word_list = self.word_list.sort()
def num_words(self):
self.num_words = len(self.word_list)
test = Word_Parser("mary had a little lamb")
test.parser()
test.sort_word_list()
test.num_words()
print test.word_list
print test.sort_word_list
print test.num_words
推荐答案
这里没有错误.您正在打印一个函数,这就是函数的样子.
There's no error here. You're printing a function, and that's what functions look like.
要实际调用该函数,您必须在此之后放置括号.你已经在上面这样做了.如果要打印调用函数的结果,只需让函数返回值,并将打印件放在那里.例如:
To actually call the function, you have to put parens after that. You're already doing that above. If you want to print the result of calling the function, just have the function return the value, and put the print there. For example:
print test.sort_word_list()
另一方面,如果您希望函数改变对象的状态,然后以其他方式打印状态,那也没关系.
On the other hand, if you want the function to mutate the object's state, and then print the state some other way, that's fine too.
现在,您的代码似乎在某些地方有效,但在其他地方却无效;让我们看看为什么:
Now, your code seems to work in some places, but not others; let's look at why:
parser
设置一个名为word_list
的变量,然后你打印 test.word_list
,这样就可以了.sort_word_list
设置一个名为sorted_word_list
的变量,然后您可以打印 test.sort_word_list
——即函数,而不是变量.所以,你看到了绑定方法.(此外,正如 Jon Clements 指出的那样,即使您解决了这个问题,您也会打印None
,因为这是sort
返回的内容.)num_words
设置一个名为num_words
的变量,然后您再次打印该函数——但在本例中,该变量与该函数具有相同的名称,这意味着您实际上用它的输出替换了这个函数,所以它可以工作.然而,这可能不是您想要做的.
parser
sets a variable calledword_list
, and you laterprint test.word_list
, so that works.sort_word_list
sets a variable calledsorted_word_list
, and you laterprint test.sort_word_list
—that is, the function, not the variable. So, you see the bound method. (Also, as Jon Clements points out, even if you fix this, you're going to printNone
, because that's whatsort
returns.)num_words
sets a variable callednum_words
, and you again print the function—but in this case, the variable has the same name as the function, meaning that you're actually replacing the function with its output, so it works. This is probably not what you want to do, however.
(在某些情况下,乍一看,这似乎是一个好主意——您只想计算一次,然后一遍又一遍地访问它,而无需不断地重新计算.但这不是方法.要么使用 @property
,要么使用备忘录装饰器.)
(There are cases where, at first glance, that seems like it might be a good idea—you only want to compute something once, and then access it over and over again without constantly recomputing that. But this isn't the way to do it. Either use a @property
, or use a memoization decorator.)
这篇关于“绑定方法"是什么意思错误是指当我调用函数时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!