【问题标题】:Why __repr__ and __str__ return a None value?为什么 __repr__ 和 __str__ 返回 None 值?
【发布时间】:2020-02-07 02:53:30
【问题描述】:

我第一次尝试在一个类中实现__repr____str__。然后,对于类调试,我尝试打印出class.__repr__()class.__str__() 值,但打印值为None。代码如下:

class Window(object):
    ''' implements some methods for manage the window '''


    def __new__(cls, master, width=1000, height=500):
        ''' check if the variables to pass to the __init__ are the correct data type '''

        # checking if the passed arguments are the correct type
        if not isinstance(master, Tk):
            raise TypeError("master must be Tk class type")

        if not isinstance(width, int):

            if isinstance(width, float):
                width = int(width)

            else:
                raise TypeError("width must be integer")

        if not isinstance(height, int):

            if isinstance(height, float):
                height = int(height)

            else:
                raise TypeError("width must be integer")


    def __init__(self, master, width=1000, height=500):
        ''' initialize the wnidow and set his basic options '''

        self.master = master
        self.width = width
        self.height = height


    def __repr__(self):
        repr_to_return = "__main__.Window{master=" + self.master + ", width=" + self.width + ", height=" + self.height + "}"
        return repr_to_return


    def __str__(self):
        str_to_return = "__main__.Window(master=" + self.master + ", width=" + self.width + ", height=" + self.height + ")"
        return str_to_return


# checking if the script has been executed as program or as module
if __name__ == "__main__":

    # declaring a Tk object
    root = Tk()
    win = Window(root, width=1000, height=500)

    win.__str__()

这是输出:

None
None

我确定我做错了什么。有人可以帮我找出错误。请原谅我的英语:这是我的第二语言。

【问题讨论】:

  • 你应该像这样使用:print(str(win)) 和 print(win)。
  • 因为您的__new__ 总是返回None,所以只需使用__init__ 即可

标签: python string class object repr


【解决方案1】:

我认为您的意思是用这个staticmethod 检查__init__ 参数:

    @staticmethod
    def _checkargs(master, width=1000, height=500):
        ''' check if the variables to pass to the __init__ are the correct data type '''

        # checking if the passed arguments are the correct type
        if not isinstance(master, Tk):
            raise TypeError("master must be Tk class type")

        if not isinstance(width, int):

            if isinstance(width, float):
                width = int(width)

            else:
                raise TypeError("width must be integer")

        if not isinstance(height, int):

            if isinstance(height, float):
                height = int(height)

            else:
                raise TypeError("width must be integer")

        return master, width, height

然后,在__init__ 方法中调用_checkargs() 并像这样解包:

self.master, self.width, self.height = self._checkargs(master, width, height)

你的__new__ 方法没有返回任何东西,所以我会考虑删除它。

此外,由于您的__repr____str__ 返回相同的内容,并且当没有__str__ 时,会调用__repr__,因此您可以删除您的__str__ 方法。

现在,在您的 __repr__ 方法中,您不能将 Tk 或 int 连接(添加)到字符串,因此您可以将您的 __repr__ 更改为以下内容:

    def __repr__(self):
        repr_to_return = "__main__.Window{master=" + repr(self.master) \
                         + ", width=" + str(self.width) + ", height=" \
                         + str(self.height) + "}"
        
        return repr_to_return

最后,使用print(str(object)) 代替print(object.__str__()) 并使用print(repr(object)) 代替print(object.__repr__())

另请参阅:What is the difference between @staticmethod and @classmethod?

【讨论】:

    猜你喜欢
    • 2011-04-11
    • 1970-01-01
    • 2016-10-04
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多