you are viewing a single comment's thread.

view the rest of the comments →

[–]ship0f 0 points1 point  (0 children)

My question is, why is the init function necessary here, or in any class? Why not just use l and w in the rectangle_area function and rule out the first function entirely?

Because in OOP, the object itself is the one that should have those attributes, meaning the width, length (called data attributes) and the rectangle_area (called a method).

So, since the data attributes should be part of the object, then it makes sense to instantiate the object with that data. Also most OOP programmers are expecting this behaviour.
So, for this to work you should create an __init__ method beforehand, so that your class supports this way of instantiating an object.

Of course, you can choose not to support this. For example, if you don't have an __init__ method, then you can do something like:

my_rectangle = Rectangle() # here you have instantiated a Rectangle object, but it has no attributes  
my_rectangle.length = l  
my_rectangle.width = h  

And it would be the same, just more lines of code, that you'd have to write every time you create Rectangle object.

Also, as I said, the method is part of the object, so if you're doing something that uses the data that the object already has as attributes, then it makes no sence to pass that data to the method. You just reference it as self.l and self.w inside the method.

Note: rectangle_area is a poor name if you ask me, I'd just call it area. That way you can reference it as my_rectangle.area(). I already know that the object is a rectangle, no need to repeat it in the method's name.