简体   繁体   English

Python 错误:function 未在 class 中定义

[英]Python error: function not defined in class

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.我刚刚开始学习 python 并在 Java 中有一点背景,并且每当我尝试运行我的代码时都会遇到这个错误。 output and error message output 和错误信息

输出和错误信息

Here are the methods I've wrote in this class.以下是我在此 class 中编写的方法。 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.我不明白为什么我不能从同一个 class 调用另一种方法。

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.要访问同一个 class 中的方法,您必须使用单词self .. 为了使该单词有效,每个方法都必须将其作为其第一个参数。

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然后在 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请务必考虑 python 的制表符,因为 stackoverflow 不允许我这样做,或者我不知道该怎么做

class Hello:

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

        
hello = Hello()

hello.main()

Thank you谢谢

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 中添加 self ,将其传递给每个方法并在调用方法和引用变量时使用它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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