Change class variable reference within the class

前端 未结 1 1611
猫巷女王i
猫巷女王i 2021-01-29 08:25

I want to be able to change the reference of a variable within the class Test

class Test():
    def change(self, Other_Class):
        self.__class__ = Other_Cla         


        
1条回答
  •  离开以前
    2021-01-29 08:52

    Inside Test.change, that self is a parameter, and parameters are just local variables.

    And rebinding local variables doesn't have any effect on anything outside of the function.

    In particular, it has no effect on any other variables (or list elements, or attributes of other objects, etc.), like the global a, that were also bound to the same value. They remain names for that same value.

    It's not even clear what you're trying to do here. You change the type of a into the type of b, and that works. But what else do you want to do?

    Do you want to change a into the object b, with the same identity? If so, you don't need any methods for that; that's what a = b means. Or do you want to be a distinct instance, but share an instance __dict__? Or to copy all of b's attributes into a? Shallow or deep? Should any extra attributes a had lying around be removed as well? Do you only care about attributes stored in the __dict__, or do you need, e.g., __slots__ to work?

    Anyway, something that might be reasonable, for some strange use case, is this:

    def change(self, other):
        inherited = dict(inspect.getmembers(self.__class__))
        for name, value in inspect.getmembers(self):
            if name not in inherited and not name.startswith('__'):
                delattr(self, name)
        self.__class__ = other.__class__
        inherited = dict(inspect.getmembers(other.__class__))
        for name, value in inspect.getmembers(other):
            if name not in inherited and not name.startswith('__'):
                setattr(self, name, value)
    

    Whether that's useful for your use case, I have no idea. But maybe it gives you an idea of the kinds of things you can actually do with the Python data model.

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