[英]Catching TypeError: Missing 1 required positional argument: 'self'
I wonder if it's possible to catch the TypeError thrown when a user calls an instance method without instantiation.我想知道当用户在没有实例化的情况下调用实例方法时是否可以捕获抛出的 TypeError 。 Something to allow me to write an exception message like:
允许我编写异常消息的东西,例如:
"Class instance is required for 'this_method'"
, instead of "Class instance is required for 'this_method'"
,而不是
"Missing 1 required positional argument: 'self'"
. "Missing 1 required positional argument: 'self'"
。
Here is a simple code snipped of Calc class with classmethod called addtwo that simply adds two numbers:下面是 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))
If you run this, you will get:如果你运行这个,你会得到:
TypeError: addtwo() missing 1 required positional argument: 'self'
which is the exact error that you encountered.这是您遇到的确切错误。 According to your requirements, it can be easily fixed by enclosing the code inside a try-except block like this:
根据您的要求,可以通过将代码包含在 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")
and on running this, you will get:运行它,你会得到:
Class instance is required for this_method
However, the standard way of calling a class method should be like this:但是,调用 class 方法的标准方法应该是这样的:
if __name__=='__main__':
instance = Calc()
print(instance.addtwo(a=2,b=4))
Hope it helped.希望它有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.