[英]passing self with other argument on function call python
我有一个小问题,下面有我的代码。 我想在 main() class 中用两个 arguments 调用“speak”function。当我调用 speak 时,它说 self 未定义,我不知道如何让它工作......有什么想法吗?
class main():
def blueon(self):
print("teste")
def speak(self,fala):
self.blueon
print(fala)
speak("testeaaaaa")
尝试这样的事情。 评论解释变化
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
你以错误的方式运行speak()
。
首先,您必须创建 class m = main()
的实例,然后使用m.speak("text")
。
你必须处理不同的信息。
顺便说一句:对于类使用CamelCaseName
有一个很好的规则 - class Main():
- 它有助于在代码中识别 class,并且它允许执行main = Main()
。
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.