【发布时间】:2013-04-26 15:08:15
【问题描述】:
我试图在 python 中创建一个简单的Rectangle-class,但我还需要在我的代码中使用点和大小,所以我试图从Point 和@987654324 继承我的Rectangle @。
问题是,我的Rectangle 的初始化方法看起来很糟糕,我不确定它是否适合任何代码。
这是我得到的:
class Size:
def __init__(self, width=0, height=0):
self.width = width
self.height = height
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
class Rectangle(Size, Point):
def __init__(self, size=None, position=None): #I'd rather not use 4 variables
if size:
super(Size, self).__init__(size.width, size.height)
else:
super(Size, self).__init__()
if position:
super(Point, self).__init__(position.x, position.y)
else:
super(Point, self).__init__()
但是,它看起来很糟糕,甚至不起作用:TypeError: object.__init__() takes no parameters
有没有更清洁的方法来做到这一点?
我当然可以强制我的矩形采用size 和position(不要让它们成为可选),但我宁愿不这样做。
我还可以将我的Rectangle 定义为与Size 和Point 的has-a 关系而不是is-a 关系,但这甚至不是正确的OOP,我主要在这里学习所以我宁愿不这样做那个。
【问题讨论】:
标签: python class inheritance python-3.x multiple-inheritance