显而易见的解决方案是使用组合/委托而不是继承:
class Parent(object):
def __init__(self, name, number):
self.name = name
self.number = number
class Child(object):
def __init__(self, parent, other):
self.parent = parent
self.other = other
def __getattr__(self, name):
try:
return getattr(self.parent, name)
except AttributeError, e:
raise AttributeError("Child' object has no attribute '%s'" % name)
p = Parent("Foo", 42)
c = Child(p, "parrot")
print c.name, c.number, c.other
p.name = "Bar"
print c.name, c.number, c.other
这当然是假设你真的不想要“副本”而是“引用”.如果你真的想要一个副本,它也是可能的,但它可能会变得棘手的可变类型:
import copy
class Parent(object):
def __init__(self, name, number):
self.name = name
self.number = number
class Child(object):
def __init__(self, parent, other):
# only copy instance attributes from parents
# and make a deepcopy to avoid unwanted side-effects
for k, v in parent.__dict__.items():
self.__dict__[k] = copy.deepcopy(v)
self.other = other
如果这些解决方案都不符合您的需求,请解释您的实际用例 – 您可能遇到XY问题.
[编辑]确实接近XY问题.真正的问题是:“我如何将peewee.Model的字段复制到另一个peewee.Model.peewee使用描述符(peewee.FieldDescriptor)来控制对模型字段的访问,并将字段名称和定义存储在模型的_meta.fields字典中,所以最简单的解决方案是迭代源模型的_meta.fields键并使用getattr / setattr:
class RevisionMixin(object):
@classmethod
def copy(cls, source, **kw):
instance = cls(**kw)
for name in source._meta.fields:
value = getattr(source, name)
setattr(instance, name, value)
return instance
class Person(peewee.Model):
# fields defintions here
class PersonRevision(Person, RevisionMixin):
# additional fields definitions here
p = Person(name="foo", number=42)
r = PersonRevision.copy(p, whatelse="parrot")
NB:未经测试的代码,从未使用过peewee,可能还有更好的事情……