简体   繁体   English

在 function 调用 python 时将自己与其他参数传递

[英]passing self with other argument on function call python

I have a little problem, I have my code below.我有一个小问题,下面有我的代码。 I want to call the "speak" function with two arguments inside the main() class. When I call speak it says that self its not defined, and i don't know how to make it work... Any ideas?我想在 main() class 中用两个 arguments 调用“speak”function。当我调用 speak 时,它说 self 未定义,我不知道如何让它工作......有什么想法吗?

class main():

    def blueon(self):
        print("teste")


    def speak(self,fala):
        self.blueon
        print(fala)

    speak("testeaaaaa")

Try something like this.尝试这样的事情。 Comments explain changes评论解释变化

class Main:      # Class name capitalized and no parenthesis if the class has no base classs
    def __init__(self):  # class constructor. Initialize here your variables
        pass

    # if you have a function that doesn't use self, you can declare it static
    @staticmethod          
    def blueon():     
        print("teste")

    def speak(self, fala):
        self.blueon()   # added missing parenthesis
        print(fala)

if __name__ == "__main__":  # add this so you can later import your class as a library without executing your test code
    m = Main()   # instantiate the class
    m.speak("testeaaaaa")   # call the speak method

You run speak() in wrong way.你以错误的方式运行speak()

First you have to create instance of class m = main() and later use m.speak("text") .首先,您必须创建 class m = main()的实例,然后使用m.speak("text")

And you have to do with different indetation.你必须处理不同的信息。

BTW: There is good rule to use CamelCaseName for classes - class Main(): - it helps to recognize class in code, and it allows to do main = Main() .顺便说一句:对于类使用CamelCaseName有一个很好的规则 - class Main(): - 它有助于在代码中识别 class,并且它允许执行main = Main()
More in PEP 8 -- Style Guide for Python Code PEP 8 中的更多内容——Python 代码的样式指南

# --- classes ---

class Main():

    def blueon(self):
        print("teste")

    def speak(self, fala):
        self.blueon()  # you forgot `()
        print(fala)

# --- main ---

main = Main()

main.speak("testeaaaaa")

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

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