Home > OS >  OOP: Why I must set the attribute parameters = None for my code to work?
OOP: Why I must set the attribute parameters = None for my code to work?

Time:07-17

I am new in coding Python and I was wondering why do I need to set my attribute parameters equal to 'None' for my code to work properly. Any advice is welcome! Thank you very much for your help! I appreciate it!

class Shape:
# I need to set w = None and h = None. Why can't I just use (self, w, h)
    def __init__(self, w = None, h = None):
        self.width = w
        self.height = h

    def area(self):
        return self.width*self.height

    def __add__(self, other):
        shp = Shape()
        shp.width = self.width   other.width
        shp.height = self.height   other.height
        return shp
    
    def __gt__(self, other):
        a1 = self.width*self.height
        a2 = other.width*other.height
        return a1 > a2

w1 = int(input())
h1 = int(input())
w2 = int(input())
h2 = int(input())

s1 = Shape(w1, h1)
s2 = Shape(w2, h2)
result = s1   s2
print(result.area())
print(s1 > s2)

CodePudding user response:

It is because you create an instance of your class Shape in the function add -> shp = Shape() without passing w and h to it. There you get an error because your class Shape expects these two arguments w and h which there aren't. If you create your class with def __init__(self, w = None, h = None): then w and h get a default value (-> None) if they aren't passed as parameter (they become optional) and creating an instance like shp = Shape() without passing w and h would be possible. I hope my explanation is understandable.

Try to do it like this:

class Shape:
    def __init__(self, w, h):
        self.width = w
        self.height = h

    def area(self):
        return self.width * self.height

    def __add__(self, other):
        return Shape(self.width   other.width, self.height   other.height)
    
    def __gt__(self, other):
        a1 = self.width * self.height
        a2 = other.width * other.height
        return a1 > a2

w1 = int(input())
h1 = int(input())
w2 = int(input())
h2 = int(input())

s1 = Shape(w1, h1)
s2 = Shape(w2, h2)
result = s1   s2
print(result.area())
print(s1 > s2)
  • Related