【发布时间】:2015-01-28 06:25:35
【问题描述】:
我想创建一个类,它具有计算字符串中单词的函数,该字符串作为参数通过函数传递(我的术语是否正确?)。这就是我所拥有的,它给了我一个错误“AttributeError:'str'对象没有属性'sentence'。
class myHacks:
def __init__(self, sentence):
self.sentence = sentence
def countWords(self):
my_list = []
my_list = self.sentence.split(" ")
counter = 0
for m in my_list:
counter += 1
return counter
myHacks.countWords("请数我")
【问题讨论】:
-
就像@JoshSmeaton 说的那样使用
collections.Counter,除非你真的想重新发明轮子。 -
str.split返回一个列表。 内置 函数len将返回列表中的项目数。无需(显式)使用计数器进行迭代和累积。
标签: python list function class loops