Python修饰类以更改父对象类型

2024-10-01 15:48:14 发布

您现在位置:Python中文网/ 问答频道 /正文

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

例如:

class X1(X):
  new_attribute = 'something'

class Y1(Y):
  new_attribute = 'something'

新的属性对于X1和Y1始终是相同的。X&Y没有任何有意义的关联,只是不可能有多重继承。还有一组其他属性,但这是退化的来说明。在

我觉得我太复杂了,但我想用一个装饰师,有点像:

^{pr2}$

我觉得我错过了一个相当普遍的模式,我将非常感谢你的想法、意见和反馈。在

谢谢你的阅读。在

布莱恩

编辑:示例:

这里有一个相关的摘录,可能会有所启发。常见类别如下:

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:... }

我一直搞不懂为什么东西有时会有它的-AccessParent属性,而有时却没有。在


Tags: thetonewdb属性itattributepass
3条回答

使用3个参数type

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

正如你所猜测的,这确实是一个相当流行的成语。在

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

^{pr2}$

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

你为什么不能用multiple inheritance?在

class Origin:
  new_attribute = 'something'

class X:
  pass

class Y:
  pass

class X1(Origin, X):
  pass

class Y1(Origin, Y):
  pass

回复您对voyager's answer的评论:

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

结果是

^{pr2}$

这不是你想要的吗?在

相关问题 更多 >

    热门问题