假设您有两个类X&是的。您希望通过向类添加属性来生成新类X1和Y1来装饰这些类。

例如:

class X1(X):
  new_attribute = 'something'

class Y1(Y):
  new_attribute = 'something'
X1和Y1的

new_attribute 始终相同。 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会有以下属性:

 Thing { it: ... }

其他时间:

 Thing { it: ..., users_permitted:..., owner:... }

我一直无法弄清楚为什么Thing有时会拥有_AccessParent属性,有时则没有。

有帮助吗?

解决方案

使用3参数输入

def makeSomeNicelyDecoratedSubclass(someclass):
  return type('MyNiceName', (someclass,), {'new_attribute':'something'})

正如你所推测的那样,这确实是一个相当受欢迎的习语。

编辑:在一般情况下,如果someclass有自定义元类,您可能需要提取并使用它(使用1参数 type )代替 type 本身,以保留它(这可能适用于您的Django和App Engine模型):

def makeSomeNicelyDecoratedSubclass(someclass):
  mcl = type(someclass)
  return mcl('MyNiceName', (someclass,), {'new_attribute':'something'})

这也适用于上面更简单的版本(因为在简单的情况下没有自定义元类 type(someclass)是type )。

其他提示

回应您对旅行者回答的评论

from google.appengine.ext import db

class Mixin(object):
    """Mix in attributes shared by different types of models."""
    foo = 1
    bar = 2
    baz = 3

class Person(db.Model, Mixin):
    name = db.StringProperty()

class Dinosaur(db.polymodel.PolyModel, Mixin):
    height = db.IntegerProperty()

p = Person(name='Buck Armstrong, Dinosaur Hunter')
d = Dinosaur(height=5000)

print p.name, p.foo, p.bar, p.baz
print d.height, d.foo, d.bar, d.baz

运行结果

Buck Armstrong, Dinosaur Hunter 1 2 3
5000 1 2 3

这不是你的想法吗?

为什么不能使用多重继承

class Origin:
  new_attribute = 'something'

class X:
  pass

class Y:
  pass

class X1(Origin, X):
  pass

class Y1(Origin, Y):
  pass
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top