简体   繁体   中英

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). 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. So i tried to use print instead of return, but it raises an error: "__str__ returned non-string (type NoneType)" . How do i print the str and also not raise an error? 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM