简体   繁体   中英

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

What is the problem here? Have tried everything! I have tried indenting and the object is created but the method my_first_test is not called/used by object c.

You are pretty close. Try this:

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

Look at this for inspiration: https://jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/

Notice the changes I've made:

  • Indented yo = input("Enter your string here") and formatted the text string a bit
  • Indented the entire my_first_test method
  • Added self to the method - read about why that's the case here: What is the purpose of self?

Results

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM