簡體   English   中英

Python:調用類方法而不是父構造方法

[英]Python: Calling class method instead of parent constructor

說我有以下類定義:

class WorldObject(pygame.sprite.Sprite):

    @classmethod
    def fromImgRect(cls, rect, image, collideable = True):
        return cls(rect.left, rect.top, rect.width, rect.height, image, collideable)        

    def __init__(self, x, y, w, h, image, collideable = True):
        self.rect = pygame.rect.Rect(x,y,w,h)
        self.collideable = collideable
        self.image = image

然后,我有以下子課程:

class Doodad(WorldObject):    
    def __init__(self,c1x, c1y, c2x, c2y, color = (200,0,180)):
        self.color = color
        self.rect = orderPoints(c1x, c1y, c2x, c2y)
        x1 = self.rect.left
        y1 = self.rect.top
        w = self.rect.width
        h = self.rect.height
        super(Doodad, self).__init__(x1,y1,w,h,self.surface, False)

這很好用,但是在我的整個代碼中都self.rect像這樣對self.rect進行解壓縮,而不是只在class方法中執行一次。 這在我的項目的許多地方都在發生,其中一些方法返回一個矩形對象,但是我需要將坐標傳遞給超級構造函數。 使所有內容返回坐標或矩形似乎是不可能的,有時候做一個或另一個更有意義。 由於python不支持重載方法,因此我希望能夠使用class方法來初始化對象。 但是我還不能弄清楚語法。 這可能嗎? 如果是這樣,怎么辦?

在您的情況下,我將添加一種“子初始化”的方法。 這將對給定的數據進行后處理:

class WorldObject(pygame.sprite.Sprite):

    @classmethod
    def fromImgRect(cls, rect, *a, **k):
        return cls(rect.left, rect.top, rect.width, rect.height, *a, **k)

    def __init__(self, x, y, w, h, image, collideable=True):
        self._init_coords(x, y, w, h)
        self.collideable = collideable
        self.image = image

    def _init_coords(self, x, y, w, h):
        self.rect = pygame.rect.Rect(x,y,w,h)

然后,您可以具有以下子類:

class Doodad(WorldObject):
    def _init_coords(self, c1x, c1y, c2x, c2y):
        self.rect = orderPoints(c1x, c1y, c2x, c2y)

    def __init__(self,c1x, c1y, c2x, c2y, color=(200, 0, 180)):
        super(Doodad, self).__init__(c1x, c1y, c2x, c2y, self.surface, False)
        self.color = color

此外,您可能想擁有

def unpack_rect(rect):
    return rect.left, rect.top, rect.width, rect.height

你甚至可以擁有

class WorldObject(pygame.sprite.Sprite):

    def __init__(self, *a, **k):
        if hasattr(a[0], 'left'):
            rect = a[0]
            self._init_coords(rect.left, rect.top, rect.width, rect.height)
            rest = a[1:]
        else:
            self._init_coords(*a[0:4])
            rest = a[4:]
        self._init_rest(*rest, **k)

    def _init_coords(self, x, y, w, h):
        self.rect = pygame.rect.Rect(x,y,w,h)

    def _init_rest(self, image, collideable=True):
        self.collideable = collideable
        self.image = image


class Doodad(WorldObject):
    def _init_coords(self, c1x, c1y, c2x, c2y):
        self.rect = orderPoints(c1x, c1y, c2x, c2y)

    def _init_rest(color=(200, 0, 180)):
        super(Doodad, self)._init_rest(self.surface, False)
        self.color = color

(我沒有在此處更改self.surface ,但目前尚未定義。您應該更改它。)

暫無
暫無

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

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