def count_words(filename):try:with open (filename) as f_obj:contents = f_obj.read()except FileNotFoundError:msg = 'Sorry,the file ' + filename + ' does not exist.'print(msg)else:words = contents.split()num_words = len (words)return str(num_words)f_obj = 'x.txt'print (f_obj.count_words())这会报错'str' has no attribute 'count_words'正确的是print(count_words(f_obj))为什么?我看有说w.f() 是调用对象w中的f方法,那对象有什么限制吗
1 回答

www说
TA贡献1775条经验 获得超8个赞
f_obj是一个str类型的变量
而str类里没有count_words()方法,所以报错
count_words()是一个独立的函数,它不属于任何类,因此调用形式就是count_words(参数)
添加回答
举报
0/150
提交
取消