[英]How to call method in the class?
我正在使用課程來練習,但我不知道如何正確使用它們。
這里我想把class放在另一個文件里,里面的代碼是:
class TestClass:
def repeat(txt:str, num:int):
counter = 0
while counter < num:
print(txt)
counter = counter + 1
創建 object 后無法調用該方法。這是代碼:
testing2 = testing.TestClass()
testing2.repeat('test', 10)
錯誤:
#the error is: TypeError: TestClass.repeat() takes 2 positional arguments but 3 were given
我認為這是一個小問題,但解釋它的解決方案將對我的理解有很大幫助。
class TestClass:
def repeat(self, txt:str, num:int):
counter = 0
while counter < num:
print(txt)
counter = counter + 1
向 def 定義添加一個參數 ( self
)。 您還可以像這樣初始化 class:
testing2 = TestClass()
testing2.repeat('test', 10)
創建class時,需要遵循class實現的基本原則。 你忘了__init__
function 初始化你 class,你的代碼需要看起來像:
class TestClass:
def __init__(self):
super().__init__()
def repeat(self, txt:str, num:int):
counter = 0
while counter < num:
print(txt)
counter = counter + 1
然后一切都會起作用
testing2 = TestClass()
testing2.repeat('test', 10)
#test
#test
#test
#test
#test
#test
#test
#test
#test
#test
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.