0

I'm just starting to learn python with a little background in Java and keep running into this error whenever I try to run my code. output and error message

output and error message

Here are the methods I've wrote in this class. methods involved, aside from the very last one

methods involved, aside from the very last one

I've checked multiple times and it isn't a spelling error. I don't understand why I'm not able to call one method in another from the same class.

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
  • 2
    [Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question) – Selcuk Feb 25 '21 at 05:12

3 Answers3

1

For you to access methods within the same class, you have to use the word self.. And for that word to be valid, each method has to have it as its first parameter.

That is to say, you would have defined the above methods as follows::

def main(self): self.run()

then on run:: def run(self): #do your stuff down here

please do take into consideration the tabbing character of python as stackoverflow hasn't allowed me to do that, or I am less informed of how to do it

emanuel sanga
  • 815
  • 13
  • 17
1
class Hello:

    def main(self):
        print("print")
        self.run()
    def run(self):
        print("run")

        
hello = Hello()

hello.main()

Thank you

Ankit Sagar
  • 176
  • 1
  • 1
  • 8
  • This should work in outside class mechanism(function based).... But for methods in class, order is not that much useful – emanuel sanga Feb 25 '21 at 05:20
  • 1
    Yash, I did saw the concept and got too know that self term if more useful thank you for letting me know!! – Ankit Sagar Feb 25 '21 at 05:50
  • Please add some explanation. – Sabito stands with Ukraine Feb 25 '21 at 05:52
  • @Yatin, self keyword carries the instance of the class so that it is possible to access the methods in that class(regardless of their positions). Normally, without a class, you need to define a method first before referencing to it. This is because python is interpreted from top to bottom – emanuel sanga Feb 25 '21 at 06:07
  • @Yatin, you can read more from this https://stackoverflow.com/questions/1590608/is-it-possible-to-forward-declare-a-function-in-python – emanuel sanga Feb 25 '21 at 06:08
1

You need to add self throughout the class, passing it to each method and using it when calling the methods and referring to variables.

class RPS:
    def main(self):
        print ("Let's play some RPS.")
        self.run()

    def run(self):
        self.compTurn()

    def compTurn(self):
        compRo11 = 1

        if compRo11 == 1:
            compRo11 = 'rock'
        elif compRo11 == 2:
            compRo11 = 'paper'  
        elif compRo11 == 3:
            compRo11 = 'scissors'

        print(compRo11)

    def usrTurn(self,compRo11):
        pass

rps = RPS()

rps.main()
norie
  • 9,609
  • 2
  • 11
  • 18