【发布时间】:2016-05-08 14:28:52
【问题描述】:
在 Python 3.x 中,是否可以创建一个可以被许多类重用的“模板”属性?
我有大约 200 个类别,对应于商店中销售的产品。每个类都使用特定于产品的属性。每个属性的“get”和“let”函数有时会在设置属性值时对数据执行详细的完整性检查。
有时对许多不同类的许多不同属性执行相同的检查。唯一改变的是属性名称。下面为“Robot”和“Box”类提供了一个简化示例。在这些类中,属性检查它是否被设置为小于 1 的值并更正它。
class Robot():
def setPrice(self,Price): # <--
# <--
if (Price < 1): Price = 1 # <--
# <-- Common check
self.__Price = Price # <-- to many
# <-- classes
def getPrice(self): # <--
# <--
return self.__Price # <--
# <--
Price = property(getPrice, setPrice) # <--
class Box():
def setWeight(self,Weight): # <--
# <--
if (Weight < 1): Weight = 1 # <--
# <-- Common check
self.__Weight = Weight # <-- to many
# <-- classes
def getWeight(self): # <--
# <--
return self.__Weight # <--
# <--
Weight = property(getWeight, setWeight) # <--
是否可以将此属性隔离到某种类的外部函数中,然后我的许多类都可以调用它?换句话说,这样的事情可以实现吗?
class_or_function TemplateProperty():
... some code ...
class Robot():
Price = TemplateProperty()
NumberOfLegs = TemplateProperty()
class Box():
Price = TemplateProperty()
Weight = TemplateProperty()
Height = TemplateProperty()
Length = TemplateProperty()
【问题讨论】:
-
为什么不把通用属性放在一个基类中呢?
-
@Blckknght:我更新了我的问题。需要模板的属性具有相同的行为,但每个类中的名称不同。可以用基类管理吗?
标签: class python-3.x object properties