我正在使用继承的面向对象方法来解决问题,我想知道如何将“鸭打字”原则应用于此问题。如何有效地继承使用鸭打字
我有一个类BoxOfShapes
这将与Shapes
(Circle
,Square
和Rectangle
)名单中实例化
import numpy as np
class Shape(object):
def __init__(self,area):
self.area = area;
def dimStr(self):
return 'area: %s' % str(self.area)
def __repr__(self):
return '%s, %s' % (self.__class__.__name__, self.dimStr()) + ';'
class Circle(Shape):
def __init__(self,radius):
self.radius = radius
def dimStr(self):
return 'radius %s' % str(self.radius)
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def dimStr(self):
return '%s x %s' % (str(self.width), str(self.height))
class Square(Rectangle):
def __init__(self, side):
self.width = side
self.height = side
class BoxOfShapes(object):
def __init__(self, elements):
self.elements = elements
def __repr__(self):
pass
listOfShapes = [Rectangle(10,13),Rectangle(9,5),Circle(12),Circle(8),Circle(36),Square(10)]
myBox = BoxOfShapes(listOfShapes)
print myBox
所以让我们看看BoxOfShapes
的__repr__()
方法。据我了解,鸭打字的实施会是这样的,
def __repr__(self):
return str(self.elements)
因为这样说:“我不在乎我有什么样的元素,只要它们实现__str__()
或__repr__()
。这个输出是
>>> print myBox
[Rectangle, 10 x 13;, Rectangle, 9 x 5;, Circle, radius 12;, Circle, radius 8;, Circle, radius 36;, Square, 10 x 10;]
可以说,我想从BoxOfShapes
更可读的输出 - 我知道所有的形状是某些类型的,所以这将是很好的分类,他们就像这样:
def __repr__(self):
circles = [ el.dimStr() for el in self.elements if isinstance(el, Circle)]
squares = [ el.dimStr() for el in self.elements if isinstance(el, Square)]
rectangles = [el.dimStr() for el in self.elements if (isinstance(el, Rectangle) and not isinstance(el, Square)) ]
return 'Box of Shapes; Circles: %s, Squares: %s, Rectangles: %s;' % (str(circles), str(squares), str(rectangles))
这样做的输出,
>>> print myBox
Box of Shapes; Circles: ['radius 12', 'radius 8', 'radius 36'], Squares: ['10 x 10'], Rectangles: ['10 x 13', '9 x 5'];
哪一个更容易阅读,但我不再使用鸭打字,现在我不得不改变我的BoxOfShapes
定义每当我想到一种新的形状。
我的问题是(如何)将这种情况下应用鸭子打字?
'__repr__'应该是不太模糊,你正在使用。特别是,它应该使用元素“__repr__”,它应该可能显示元素的顺序。要尝试的一件好事是制作'eval(repr(thing))== thing',或者尽可能地接近你的想法。我推荐'返回'BoxOfShapes({})'。格式(repr(self.elements))' – user2357112
如果你想要一些漂亮而且容易理解的东西,那就是'__str__'的用途。 – user2357112
与那些'type()'静态方法有什么关系?你应该可能会失去它们。如果你需要一个对象类型的名字,那么就有内建的'type()'函数和类型的__name__'属性(并且通常不用,你可以使用类型对象而不是用名字来混淆) )。 – delnan