Python Forum
Confusion about TypeError and 'self'
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Confusion about TypeError and 'self'
#1
Hey everyone, this is my first post so I hope this is clear.
I am working on some code where the user is asked to select from a comboBox.

This problem I have is the code is suggesting I need to include the self argument however when I include it, it still errors out. I've gone around in circles for a couple of days now. Your insights would be greatly appreciated.

WITHOUT SELF ARGUMENT
    def play(self):
        guess = str(self.ui.comboBox.currentText())
        return guess

    if play() == comp_num:
        winmessage()
    else:
        losemessage()
And this is the Error
Error:
Traceback (most recent call last): File "D:/Muzzrooms/Desktop/Year 11/Term 2/Digital Solutions/Guessing Game/Guessing_game_completed.py", line 15, in <module> class MainWindow: File "D:/Muzzrooms/Desktop/Year 11/Term 2/Digital Solutions/Guessing Game/Guessing_game_completed.py", line 43, in MainWindow if play() == comp_num: TypeError: play() missing 1 required positional argument: 'self'
WITH SELF ARGUMENT
    def play(self):
        guess = str(self.ui.comboBox.currentText())
        return guess

    if play(self) == comp_num:
        winmessage()
    else:
        losemessage()
And this is the error I receive if I include the self argument.
Error:
Traceback (most recent call last): File "D:/Muzzrooms/Desktop/Year 11/Term 2/Digital Solutions/Guessing Game/Guessing_game_completed.py", line 15, in <module> class MainWindow: File "D:/Muzzrooms/Desktop/Year 11/Term 2/Digital Solutions/Guessing Game/Guessing_game_completed.py", line 43, in MainWindow if play(self) == comp_num: NameError: name 'self' is not defined
Your help is greatly appreciated;
-Muzzrooms
Reply
#2
Showing all your code would be helpful.

My guess is you have written a class and play is one of the methods of the class. To call a method the correct syntax is object.method(arguments). Python uses the object to find out where to look for method. It then calls the method like this "method(object, arguments).

Somewhere you are creating an instance of you class and hopfully keeping the returned object in a variable. Something like this:

myobject = MyClass(maybe, some, args)

To call the play method you would type:

myobject.play()
Reply
#3
def play(self):
    guess = str(self.ui.comboBox.currentText())
    return guess
 
if self.play() == comp_num: # Self may need to be changed to the name of the object depending on usage.
    winmessage()
else:
    losemessage()
Because play() is evidently a method, it must be prefaced by a reference to the instance running the method. When called within a method of the class, it must be prefaced with "self.". Otherwise, it lacks an argument for that parameter.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020