How to copy all properties of an object to another object, in Python?

后端 未结 5 1257
自闭症患者
自闭症患者 2020-12-02 16:30

Is there a library method to copy all the properties between two (already present) instances of the same class, in Python?

I mean, something like Apache Commons\'

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 17:18

    If you have to do this, I guess the nicest way is to have a class attribute something like :

    Class Copyable(object):
        copyable_attributes = ('an_attribute', 'another_attribute')
    

    Then iterate them explicitly and use setattr(new, attr, getattr(old, attr)). I still believe it can be solved with a better design though, and don't recommend it.

提交回复
热议问题