简体   繁体   English

如何使用实例激活 __str__ dunder 方法并修复错误:“__str__ 返回非字符串(类型 NoneType)”

[英]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.

相关问题 IN ADMIN PANEL __str__ 返回非字符串(NoneType 类型) - IN ADMIN PANEL __str__ returned non-string (type NoneType) TypeError:__str__返回了非字符串(类型NoneType) - TypeError: __str__ returned non-string (type NoneType) TypeError:__str__ 在 Django 中返回非字符串(类型 NoneType) - TypeError: __str__ returned non-string (type NoneType) in Django __str__ 返回非字符串(类型 NoneType)...我收到此错误可能是由于 NoneType 用户 model - __str__ returned non-string (type NoneType)...im receiving this error may be due to a NoneType user model 如何修复 TypeError __str__ 返回的非字符串 - How to fix TypeError __str__ returned non-string “__str__ 返回非字符串(int 类型)”错误 - Error with "__str__ returned non-string (type int)" __str__ 在 Django 管理菜单中尝试保存时返回非字符串(类型 NoneType)错误 - __str__ returned non-string (type NoneType) error when trying to save in Django admin menu 如何使用带有外键 '__str__ 的 __str__ 返回非字符串(产品类型)' - how to use __str__ with foreign key '__str__ returned non-string (type Product)' TypeError: __str__ 返回非字符串(NoneType 类型)。 不知道如何解决这个问题 - TypeError: __str__ returned non-string (type NoneType). Not sure how to solve this TypeError:__str__返回了非字符串(类型元组) - TypeError: __str__ returned non-string (type tuple)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM