Python 3中未解决的属性参考

时间:2018-07-18 06:07:37

标签: python python-3.x pycharm

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。

1 个答案:

答案 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()

看一下这个灵感:https://jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/

注意我所做的更改:

  • 缩进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