Can I efficiently swap two class instances by swapping __dict__?

后端 未结 4 1176
别那么骄傲
别那么骄傲 2021-01-08 00:03

I have a big class with lots of members, and quite a few references to instances of this class lying around. Unfortunately (for reasonable reasons) all these references are

4条回答
  •  孤街浪徒
    2021-01-08 00:38

    For your own sanity, and that of whoever may use your code after you, if you decide to use this function, you should document the hell out of it so that you know what's going on. Your more self-documenting alternative, of course, is to write a function that swaps all the data members individually. Obviously this isn't very future-proof if your data model will be changing, but it will be less confusing. If it's not something you want to write out by hand, you could define a function to swap one data field, and run it over all your class attributes:

    def swap (a, b):
      for key in a.__dict__.keys():
        swapOneField(key, a, b)
    

    and for swapOneField get the values from a.__dict__ and b.__dict__ and use the swapping algorithm of your choice. It's more verbose, and probably less efficient, but if you save more time in not debugging it than you lose in running it, it's probably worth your time.

提交回复
热议问题