簡體   English   中英

捕獲 TypeError:缺少 1 個必需的位置參數:'self'

[英]Catching TypeError: Missing 1 required positional argument: 'self'

我想知道當用戶在沒有實例化的情況下調用實例方法時是否可以捕獲拋出的 TypeError 。 允許我編寫異常消息的東西,例如:

"Class instance is required for 'this_method'" ,而不是

"Missing 1 required positional argument: 'self'"

下面是 Calc class 的一個簡單代碼,其類方法名為 addtwo,它簡單地將兩個數字相加:

class Calc():
    a: int
    b: int
    
    def addtwo(self,a,b):
        self.a=a
        self.b=b
        return self.a+self.b
        
if __name__=='__main__':
        print(Calc.addtwo(a=2,b=4))

如果你運行這個,你會得到:

TypeError: addtwo() missing 1 required positional argument: 'self'

這是您遇到的確切錯誤。 根據您的要求,可以通過將代碼包含在 try-except 塊中來輕松修復,如下所示:

class Calc():
    a: int
    b: int
    
    def addtwo(self,a,b):
        self.a=a
        self.b=b
        return self.a+self.b
        
if __name__=='__main__':
    try:
        print(Calc.addtwo(a=2,b=4))
    except TypeError:
        print("Class instance is required for this_method")

運行它,你會得到:

Class instance is required for this_method

但是,調用 class 方法的標准方法應該是這樣的:

if __name__=='__main__':
    instance = Calc()
    print(instance.addtwo(a=2,b=4))

希望它有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM