I'm trying for the first time to implement __repr__
and __str__
in a class. Then, for the class debugging I tried to print out the class.__repr__()
and the class.__str__()
value but the printing value is None
. Here is the code:
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__()
And here is the output:
None
None
I'm sure I'm doing something wrong. Can someone help me out to figure out the error. And please excuse my English: it is my second language.