【发布时间】:2021-02-25 02:21:49
【问题描述】:
我正在寻找一种将通用属性装饰器添加到类的速记。
class Animal:
def __init__(self):
self._attributes = {}
class Dog(Animal):
@property
def color(self):
return super()._attributes.get('color', None)
@color.setter
def color(self, value):
if value is not None:
super()._attributes['color'] = value
else:
super()._attributes.pop('color', None)
class Cat(Animal):
@property
def color(self):
return super()._attributes.get('color', None)
@color.setter
def color(self, value):
if value is not None:
super()._attributes['color'] = value
else:
super()._attributes.pop('color', None)
class InvisibleMan(Animal):
pass
我正在寻找“打包”颜色属性的最简单方法,以便我可以将其分配给 Dog 和 Cat,而不是 InvisibleMan。像这样的东西(虽然实际上会有大约 8 个这样的属性和大约 15 个这样的类)
class Dog(Animal):
def __init__(self):
super().__init__()
includeColorProperty(self)
【问题讨论】:
-
为什么不直接在
Animal类中添加呢?
标签: python-3.x oop inheritance decorator