假设我有以下类定义:
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
,而不是在class方法中只做一次,这很烦人。这在我的项目中的许多地方都发生过,我的一些方法返回一个矩形对象,但我需要将坐标传递给一个超级构造函数。看起来不可能让所有的东西都返回坐标或矩形,有时做一个或另一个更有意义。因为python不支持重载方法,所以我希望能够使用class方法初始化对象。但是我还没有弄清楚语法。这可能吗?如果是,怎么做?你知道吗
在您的情况下,我将添加一个“sub initialization”方法。这将对给定数据进行后处理:
然后您可以拥有以下子类:
另外,你可能想
你甚至可以
(我没有在这里更改
self.surface
,但现在还没有定义它。你应该改一下。)相关问题 更多 >
编程相关推荐