【发布时间】: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