Reclassing an instance in Python

前端 未结 8 556
野趣味
野趣味 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. ;)

    0 讨论(0)
  • 2020-12-02 10:25

    In ojrac's answer, the break breaks out of the for-loop and doesn't test any more attributes. I think it makes more sense to just use the if-statement to decide what to do with each attribute one at a time, and continue through the for-loop over all attributes. Otherwise, I like ojrac's answer, as I too see assigning to __class__ as weird. (I'm a beginner with Python and as far as I remember this is my first post to StackOverFlow. Thanks for all the great information!!)

    So I tried to implement that. I noticed that dir() doesn't list all the attributes. http://jedidjah.ch/code/2013/9/8/wrong_dir_function/ So I added 'class', 'doc', 'module' and 'init' to the list of things to add if they're not there already, (although they're probably all already there), and wondered whether there were more things dir misses. I also noticed that I was (potentially) assigning to 'class' after having said that was weird.

    0 讨论(0)
提交回复
热议问题