Skip to content
Advertisement

str method not printing correctly

I’m working on creating a subclass Rug from a parent class rectangle for school.
Everything looks like it should be working but when I try to print the __str__ method for the subclass the only that populates from the parent class is <__main__.Rug object at 0x0000019C2B69C400>.

This is my Parent Class :

import math

class Rectangle:
    
    def __init__(self, l, w):
        self.setLength(l)
        self.setWidth(w)
        
    def getLength(self):
        return self.__length

    def setLength(self, l):
        if l < 0:
            l = 1
        self.__length = l

    def getWidth(self):
        return self.__width

    def setWidth(self, w):
        if w < 0:
            w = 1
        self.__width = w

    def getArea(self):
        return self.__length * self.__width

This is my Rug subclass :

class Rug(Rectangle):

    def __init__(self, l, w, p):
        super().__init__(l, w)
        self.__price = p

    def getPrice(self):
        return self.__price

    def __str__(self):
        return super().__str__() + ", Area: " + str(self.getArea()) + ", Price: " + str(self.getPrice())

def main ():
    r = Rug(float(input("Please enter length: ")), float(input("Please enter width: ")), 150)
    print(r)

main()

This is all in Python 3.

This is my first time asking a question on here so if I need to provide anymore information like the code for my Rectangle parent class please let me know.

Any help would be appreciated!

Advertisement

Answer

Is a __str__(self) implemented in the base class? If assuming your Rectange looks like the following:

class Rectangle():

    def __init__(self, l, w):
        self.length = l
        self.width = w

    def getArea(self):
        return self.length * self.width

    def __str__(self):
        return f'Rug {self.length}x{self.width}'

Your code would print the base function’s string representation defined by it’s __str__() function.

You could use f-string interpolation to clean up your Rug.__str__() as well:

class Rug(Rectangle):
    ...
    ...
    def __str__(self):
        return f'{super().__str__()}, Area: {self.getArea()}, Price: {self.getPrice()}'
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement