[英]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.