Python修饰一个类来改变父对象类型

Bri*_*unt 3 python decorator multiple-inheritance

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

例如:

class X1(X):
  new_attribute = 'something'

class Y1(Y):
  new_attribute = 'something'
Run Code Online (Sandbox Code Playgroud)

对于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
Run Code Online (Sandbox Code Playgroud)

感觉我错过了一个相当普遍的模式,我不得不考虑思想,输入和反馈.

谢谢你的阅读.

布赖恩

编辑:示例:

这是一个可以阐明的相关提取物.常见的课程如下:

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
Run Code Online (Sandbox Code Playgroud)

这是一个子文档:

 class Thing(AccessExpando):
     it = db.StringProperty()
Run Code Online (Sandbox Code Playgroud)

有时Thing将具有以下属性:

 Thing { it: ... }
Run Code Online (Sandbox Code Playgroud)

还有其他时间:

 Thing { it: ..., users_permitted:..., owner:... }
Run Code Online (Sandbox Code Playgroud)

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

Ale*_*lli 5

使用3参数类型:

def makeSomeNicelyDecoratedSubclass(someclass):
  return type('MyNiceName', (someclass,), {'new_attribute':'something'})
Run Code Online (Sandbox Code Playgroud)

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

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

def makeSomeNicelyDecoratedSubclass(someclass):
  mcl = type(someclass)
  return mcl('MyNiceName', (someclass,), {'new_attribute':'something'})
Run Code Online (Sandbox Code Playgroud)

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