【发布时间】:2009-09-11 17:18:05
【问题描述】:
假设您有两个类 X 和 Y。您想通过向该类添加属性来装饰这些类以生成新的类 X1 和 Y1。
例如:
class X1(X):
new_attribute = 'something'
class Y1(Y):
new_attribute = 'something'
new_attribute 对于 X1 和 Y1 将始终相同。 X 和 Y 没有任何有意义的关系,除了不可能进行多重继承。还有一组其他属性,但为了说明,这是退化的。
我觉得我过于复杂了,但我曾想过使用装饰器,有点像这样:
def _xywrap(cls):
class _xy(cls):
new_attribute = 'something'
return _xy
@_xywrap(X)
class X1():
pass
@_xywrap(Y)
class Y1():
pass
感觉好像我错过了一个相当普遍的模式,我非常感谢你的想法、输入和反馈。
感谢您的阅读。
布赖恩
编辑:示例:
这是一个相关的摘录,可能会有所启发。常用的类如下:
from google.appengine.ext import db
# I'm including PermittedUserProperty because it may have pertinent side-effects
# (albeit unlikely), which is documented here: [How can you limit access to a
# GAE instance to the current user][1].
class _AccessBase:
users_permitted = PermittedUserProperty()
owner = db.ReferenceProperty(User)
class AccessModel(db.Model, _AccessBase):
pass
class AccessExpando(db.Expando, _AccessBase):
pass
# the order of _AccessBase/db.* doesn't seem to resolve the issue
class AccessPolyModel(_AccessBase, polymodel.PolyModel):
pass
这是一个子文档:
class Thing(AccessExpando):
it = db.StringProperty()
有时事物会具有以下属性:
Thing { it: ... }
还有其他时间:
Thing { it: ..., users_permitted:..., owner:... }
我一直无法弄清楚为什么 Thing 有时会有它的 _AccessParent 属性,而有时却没有。
【问题讨论】:
-
你能解释一下为什么直接在类中定义这些属性是一件坏事吗? (例如,如果有多个属性 - 但您声明 X/Y 是不相关的)在我看来,无论如何您都必须明确定义它们,并且将它们留在课堂上并不是那么糟糕。
-
@Fragsworth - 要添加的属性很多,实际上有 5+ 个 X / Y 类(X & Y 只是为了说明而退化),要添加的属性将始终相同。没有对重复属性进行某种重构来创建代码,这违反了 DRY。
标签: python decorator multiple-inheritance