Search code examples
pythonpython-class

passing self with other argument on function call python


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

I'm new to POO.

class main():

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


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

    speak("testeaaaaa")

Solution

  • You run speak() in wrong way.

    First you have to create instance of class m = main() and later use 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().
    More in PEP 8 -- Style Guide for Python Code

    # --- classes ---
    
    class Main():
    
        def blueon(self):
            print("teste")
    
        def speak(self, fala):
            self.blueon()  # you forgot `()
            print(fala)
    
    # --- main ---
    
    main = Main()
    
    main.speak("testeaaaaa")