'Python OOP Composition

class Rectangle:
    def __init__(self, width, height):
        self.width=width
        self.height=height
        
    def get_perimeter(self):
        return (self.width+self.height)*2

class Figures:
    def __init__(self, width=None, height=None):
        
        self.obj_rectangle=Rectangle(width, height)
        
    def get_rectangle(self):
        self.obj_rectangle.get_perimeter()


f = Figures()
f.get_rectangle(width=15, height=15)
TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5808/3887126288.py in <module>
----> 1 f.get_rectangle(width=15, height=15)

TypeError: get_rectangle() got an unexpected keyword argument 'width'

Why I have this problem and how can I get to fix it?



Solution 1:[1]

Functions in a class act the same as functions outside however they also take the class instance where you can access class objects and attributes. Your first class 'Figures' sets the class attribute 'obj_rectangle' to an empty rectangle where the parameters are None. You then pass in the same attributes to 'get_rectange' which doesn't take any parameters. This is the same for the 'get_parameter' method in class 'Rectangle'.

Tl;Dr; class functions do not inherit their parameters from the __init__ function and still act as normal functions other than the fact they can access class attributes.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ItzTheDodo