1

I can copy the properties of an object to another one according to this question. But in some case I just want to copy the public properties and neglect private properties or filter out some specific classes, what should I do to realize it?

Community
  • 1
  • 1
natsuapo
  • 585
  • 9
  • 22

1 Answers1

4

The described requirement is a defined predicate over the copied attributes. This can be by filtering over the keys, assuming you want to omit __* attributes:

class MyClass(object):
    def __init__(self):
        super(MyClass, self).__init__()
        self.foo = 1
        self.__bar = 2

def key_predicate(key):
    return not key.startswith('_')

obj = MyClass()
d = {k: v for k, v in obj.__dict__.items() if key_predicate(k)}

This will result:

{'foo': 1}

This can be applied on a new instance:

class MyOtherClass(object):
    pass

other_obj = MyOtherClass()
other_obj.__dict__.update(d)
assert other_obj.foo == 1
Elisha
  • 23,310
  • 6
  • 60
  • 75