python对象复制_如何将一个Python对象的所有属性复制到另一个Python对象?

本文探讨了在Python中如何利用组合和委派来替代继承,以实现更灵活的对象关系。通过示例展示了如何创建一个Child类,它引用Parent类的属性而不是复制它们。同时,提到了在需要深拷贝时可能遇到的挑战及其解决方案。最后,针对特定的Peewee ORM库,提供了一个将模型字段复制到另一模型的示例。
摘要由CSDN通过智能技术生成

显而易见的解决方案是使用组合/委派而不是继承: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,可能还有更好的事情要做。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值