2013-04-23 142 views
0

我想要一个子类的属性具有不同于它的父类的相同属性的名称,即使它意味着同样的事情。例如,父类是具有属性“高度”的Shape和具有类似属性“直径”的子类Circle。下面简单介绍一下我现在拥有的内容,但我希望Circle类使用“直径”而不是“高度”。处理这个问题的最好方法是什么?子类属性不同的名称

注意:我将从Circle继承另一个类,该类还需要使用“直径”而不是“高度”。谢谢!

class Shape(): 
    def __init__(self, shape, bar_args, height): 
     self.shape = shape 
     self.height = height 
     etc. 

class Circle(Shape): 
    def __init__(self, height, foo_args, shape='circle'): 
    Shape.__init__(self, shape, height) 
     self.height = height 
     etc. 

回答

3

你可以定义一个property它访问的读写访问原始属性:

class Circle(Shape): 
    def __init__(self, height, foo_args, shape='circle'): 
     Shape.__init__(self, shape, height) # assigns the attributes there 
     # other assignments 
    @property 
    def diameter(self): 
     """The diameter property maps everything to the height attribute.""" 
     return self.height 
    @diameter.setter 
    def diameter(self, new_value): 
     self.height = new_value 
    # deleter is not needed, as we don't want to delete this. 

如果你想这种行为非常频繁,你找物业与二传手处理和getter太不方便,你可以去迈高和build自己descriptor class

class AttrMap(object): 
    def __init__(self, name): 
     self.name = name 
    def __get__(self, obj, typ): 
     # Read access to obj's attribute. 
     if obj is None: 
      # access to class -> return descriptor object. 
      return self 
     return getattr(obj, self.name) 
    def __set__(self, obj, value): 
     return setattr(obj, self.name, value) 
    def __delete__(self, obj): 
     return delattr(obj, self.name) 

有了这个,你可以再做

class Circle(Shape): 
    diameter = AttrMap('height') 
    def __init__(self, height, foo_args, shape='circle'): 
     Shape.__init__(self, shape, height) # assigns the attributes there 
     # other assignments 

diameter描述将重定向所有访问它命名的属性(这里:height)。

+0

glglgl:非常感谢您的快速回复。如果我创建了一个继承自Circle的孙子类,并且我还想使用“直径”而不是“高度”,该怎么办?这是否意味着我必须重新做同样的@property想法?谢谢! – JasonArg123 2013-04-23 15:28:18

+0

从第三个属性中,您可以随意访问“直径”和/或“高度”。对直径的所有读取访问都被重定向到“高度”,以及所有的写入访问。 – glglgl 2013-04-23 15:33:46

+0

glglgl,这是非常好的。非常感谢! – JasonArg123 2013-04-23 17:19:13

相关问题