[英]how to activate __str__ dunder method using instance and fix error:"__str__ returned non-string (type NoneType)"
I have been trying to create a rational class, and add a __str__
dunder method to return the p(numerator), divided by the q(denominator).我一直在尝试创建一个合理的类,并添加一个
__str__
dunder 方法来返回 p( __str__
) 除以 q(denominator)。 when i try to print the object rational_1, it only gives me the output of the init method and doesn't return the __str__
dunder method at all.当我尝试打印对象rational_1 时,它只给我init方法的输出,根本不返回
__str__
dunder 方法。 So i tried to use print instead of return, but it raises an error: "__str__ returned non-string (type NoneType)"
.所以我尝试使用打印而不是返回,但它引发了一个错误:
"__str__ returned non-string (type NoneType)"
。 How do i print the str and also not raise an error?我如何打印 str 并且不引发错误? thanks!
谢谢!
import math
class Rational:
def __init__(self,p,q):
self.p=p
self.q=q
def __str__(self):
self.great_dev=math.gcd(self.p,self.q)
self.p=self.p/self.great_dev
self.q=self.q/self.great_dev
print ("{self.p}/{self.q}".format(self=self))
rational_1=Rational(3,60)
print(rational_1)
As the error says, you need to return
the new string representation of the class instance you created in the overriden __str__
dunder method.正如错误所说,您需要
return
在重写的__str__
dunder 方法中创建的类实例的新字符串表示形式。
def __str__(self):
self.great_dev=math.gcd(self.p,self.q)
self.p=self.p/self.great_dev
self.q=self.q/self.great_dev
# return the updated string representation
return "{self.p}/{self.q}".format(self=self)
Then the code will expected and the output will be 1.0/20.0
那么代码将是预期的,输出将是
1.0/20.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.