显而易见的解决方案是使用组合/委派而不是继承: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
如果这些解决方案都不符合您的需求,请解释您的real用例-您可能有XY问题。
[编辑]实际上,接近XY问题。真正的问题是:“如何将一个peewee.Model的字段复制到另一个peewee.Model中。peewee使用描述符(peewee.FieldDescriptor)控制对模型字段的访问,并将字段名称和定义存储在模型的_meta.fieldsdict中,因此最简单的解决方案是迭代源模型的_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")
注意:未经测试的代码,从未使用过peewee,可能还有更好的事情要做。。。