passing self with other argument on function call python
Question:
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")
Answers:
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.
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")
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")
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.
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")