簡體   English   中英

Python 3中未解決的屬性參考

[英]Unresolved attribute reference in Python 3

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。

你很親密 嘗試這個:

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 -在這里閱讀為什么會這樣: 自我的目的是什么?

結果

python3 untitled.py 
Enter your string here: a ab a
The number of odd words are  2
The number of even words are 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM