Reclassing an instance in Python

前端 未结 8 616
野趣味
野趣味 2020-12-02 10:07

I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class.

I now want to t

8条回答
  •  不知归路
    2020-12-02 10:25

    Heheh, fun example.

    "Reclassing" is pretty weird, at first glance. What about the 'copy constructor' approach? You can do this with the Reflection-like hasattr, getattr and setattr. This code will copy everything from one object to another, unless it already exists. If you don't want to copy methods, you can exclude them; see the commented if.

    class Foo(object):
        def __init__(self):
            self.cow = 2
            self.moose = 6
    
    class Bar(object):
        def __init__(self):
            self.cat = 2
            self.cow = 11
    
        def from_foo(foo):
            bar = Bar()
            attributes = dir(foo)
            for attr in attributes:
                if (hasattr(bar, attr)):
                    break
                value = getattr(foo, attr)
                # if hasattr(value, '__call__'):
                #     break # skip callables (i.e. functions)
                setattr(bar, attr, value)
    
            return bar
    

    All this reflection isn't pretty, but sometimes you need an ugly reflection machine to make cool stuff happen. ;)

提交回复
热议问题