【问题标题】:Inheritance creating an object - defining the size and delegating an object继承创建对象 - 定义大小和委托对象
【发布时间】:2021-06-26 16:57:38
【问题描述】:

我正在尝试解决任务,这是内容:

用x、y、w、h字段定义Rectangle类,依次存储坐标系左上角在x轴和y轴上的位置和矩形的宽高。

定义一个包含名称和颜色的Window 类。创建一个Window1 对象。将窗口的位置和大小委托给Rectangle 对象。

我的代码:

class Rectangle:
    def __init__(self, x, y, w, h):
       self.x = x
       self.y = y
       self.w = w
       self.h = h

class Window(Rectangle):
    def __set_name__(self, name):
        self.name = name
    def __set_color__(self,color):
        self.color = color

如何完成任务“创建 Window 1 对象。将窗口的位置和大小委托给 Rectangle 对象”任务的这一部分 - 能否请教如何执行此操作的提示?

【问题讨论】:

  • 子类可以“委托”给它的超类的一种方法是使用内置的super() 函数来引用它。这将通过为 Window 类定义一个 __init__() 方法来调用其超类的 __init__() 方法并将所需的参数传递给它。

标签: python function class object inheritance


【解决方案1】:

这里是解决方案。如果我的问题是正确的。

class Rectangle:
    def __init__(self, x, y, w, h):
        print(x, y, w, h)
        self.x = x
        self.y = y
        self.w = w
        self.h = h

class Window(Rectangle):

    def __init__(self, x, y, w, h):
        super().__init__(x, y, w, h)

    def __set_name__(self, name):
        self.name = name
    def __set_color__(self,color):
        self.color = color

w = Window(1, 2, 3, 4)

请随时提出任何其他问题。如果你觉得它令人困惑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-26
    • 1970-01-01
    • 2015-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    相关资源
    最近更新 更多