class StringHandling:
def __init__(self,yo):
self.yo = yo
def my_first_test():
yo = input("Enter your string here")
ya = (yo.split())
even = 0
odd = 0
for i in ya:
if len(i) % 2 == 0:
even = even + 1
else:
odd = odd + 1
print("The number of odd words are ", odd)
print("The number of even words are", even)
if __name__ == '__main__':
c = StringHandling(yo="My name is here ")
c.my_first_test()
这是什么问题?尝试了一切! 我已经尝试了缩进并创建了对象,但是对象c未调用方法my_first_test。
答案 0 :(得分:2)
您非常接近。试试这个:
class StringHandling(object):
def __init__(self,yo):
self.yo = yo
def my_first_test(self):
yo = input("Enter your string here: ")
ya = (yo.split())
even = 0
odd = 0
for i in ya:
if len(i) % 2 == 0:
even = even + 1
else:
odd = odd + 1
print("The number of odd words are ", odd)
print("The number of even words are", even)
if __name__ == '__main__':
c = StringHandling(yo="My name is here ")
c.my_first_test()
注意我所做的更改:
yo = input("Enter your string here")
并稍微格式化文本字符串my_first_test
方法self
-在这里阅读为什么会这样:What is the purpose of self? 结果
python3 untitled.py
Enter your string here: a ab a
The number of odd words are 2
The number of even words are 1