Python OOP 组合

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'

为什么我会遇到这个问题,我该如何解决?

class 中的函数与外部函数的作用相同,但它们也采用 class 实例,您可以在其中访问 class 对象和属性。您的第一个 class 'Figures' 将 class 属性 'obj_rectangle' 设置为参数为 None 的空矩形。然后,您将相同的属性传递给 'get_rectange',它不带任何参数。 class 'Rectangle'.

中的'get_parameter'方法也是如此

Tl;博士; class 函数不从 __init__ 函数继承它们的参数,除了它们可以访问 class 属性之外,它们仍然充当正常函数。