簡體   English   中英

如何從超類方法初始化子類?

[英]How to initiallize subclass from superclass method?

我在網上讀到重載構造函數的pythonic方法是創建 class 方法。 所以我創建了一個RectF class ,它可以通過兩種方式之一進行初始化。

class RectF:
    def __init__(self, x: float, y: float, w, h):
        self.x: float = x
        self.y: float = y
        self.width = w
        self.height = h

    @classmethod
    def from_tuples(cls, pos: tuple, size: tuple):
        return cls(pos[0], pos[1], size[0], size[1])

init 構造函數為每個字段接受一個參數,而from_tuples方法接受兩個分別包含坐標和大小的元組。

但是,當我在 go 初始化一個子類的實例時,使用from_tuples方法,拋出了異常。 使用super().__init__()工作正常。

class Entity(RectF):
    def __init__(self, pos: tuple, size: tuple, vel: tuple):
        super().__init__(pos[0], pos[1], size[0], size[1])

        # I would like to initialize the superclass using the from_tuples class method.
        # super().from_tuples(pos, size)
        # This throws the following exception: __init__() takes 4 positional arguments but 5 were given

        self.vel_x = vel[0]
        self.vel_y = vel[1]

上面的代碼是一個示例,現在可以正常工作。 但是為了可讀性和可維護性; 作為最佳實踐,使用最少的 arguments 初始化對象會很有用,尤其是當它們隨着時間的推移變得更加復雜時。

__init__被調用時,object 已經構建好了,所以使用from_tuples為時已晚。

不要使用 arguments 的數量作為簡單性的衡量標准。 相反,考慮哪些方法可以用來實現其他方法。 如果您希望元組成為矩形的基本構建塊,您可以這樣做:

class RectF:
    def __init__(self, pos: tuple, size: tuple):
        self.x: float = pos[0]
        self.y: float = pos[1]
        self.width = size[0]
        self.height = size[1]

    # No good name for this method comes to mind
    @classmethod
    def from_separate_values(cls, x, y, w, h):
        return cls((x, y), (w, h))


class Entity(RectF):
    def __init__(self, pos: tuple, size: tuple, vel: tuple):
        super().__init__(pos, size)
        self.vel_x = vel[0]
        self.vel_y = vel[1]

    @classmethod
    def from_separate_values(cls, x, y, w, h, vx, vy):
        rv = super().from_separate_values(x, y, w, h)
        rv.vel_x = vx
        rv.vel_y = vy
        return rv

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM