2013-08-16 15 views
1

我正在使用继承的面向对象方法来解决问题,我想知道如何将“鸭打字”原则应用于此问题。如何有效地继承使用鸭打字

我有一个类BoxOfShapes这将与ShapesCircleSquareRectangle)名单中实例化

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定义每当我想到一种新的形状。

我的问题是(如何)将这种情况下应用鸭子打字?

+0

'__repr__'应该是不太模糊,你正在使用。特别是,它应该使用元素“__repr__”,它应该可能显示元素的顺序。要尝试的一件好事是制作'eval(repr(thing))== thing',或者尽可能地接近你的想法。我推荐'返回'BoxOfShapes({})'。格式(repr(self.elements))' – user2357112

+0

如果你想要一些漂亮而且容易理解的东西,那就是'__str__'的用途。 – user2357112

+2

与那些'type()'静态方法有什么关系?你应该可能会失去它们。如果你需要一个对象类型的名字,那么就有内建的'type()'函数和类型的__name__'属性(并且通常不用,你可以使用类型对象而不是用名字来混淆) )。 – delnan

回答

1

这是不是真正的鸭打字,但关于继承一般(你可以问究竟对Java同样的问题,它没有鸭子类型的概念,例如)。

你想要做的只是创建一个字典映射类型到实例列表。这很容易做到这一点动态:

from collections import defaultdict 
type_dict = defaultdict(list) 
for element in self.elements: 
    type_dict[element.type()].append(element.dimStr()) 
return ','.join('%s: %s' for k, v in type_dict.items()) 
1

您已经为有效使用继承铺平了道路。您为每个形状定义一个type方法。只需创建一个字典,将该类型映射到您的BoxOfShapes实现中该类型的元素列表。

正如其他人所建议的,使用内置的type()函数。如果需要形状名称的字符串表示,请使用单独的实例方法。

1

这是一个解决方案

from collections import defaultdict 

class BoxOfShapes(object): 
    def __init__(self, elements): 
     self.elements = elements 
     self.groupings = defaultdict(list) 
     for element in elements: 
      self.groupings[type(element)].append(element) 

    def __repr__(self): 
     return "Box of Shapes: %s;" % ", ".join(type(group[0]).__name__ + "s: " + str(group) for group in self.groupings.itervalues()) 

这似乎并不理想,但。

更合适repr可能只是返回self.elementslen

def __repr__(self): 
    return "<%s, length=%s>" % (type(self).__name__, len(self.elements))