Skip to content Skip to sidebar Skip to footer

Override Used Classes In Parent Class

Suppose there is a class NiceClass using some other class LesserClass in a place I can't edit # NiceClass.py class LesserClass: ... # stuff ... class NiceClass: .

Solution 1:

I hope this is only limited to methods under NiceClass using the class LesserClass.

Now if you want the methods inside MyNiceClass to use MyLesserClass instead of LesserClass then you could update the __globals__ dict of those methods and make the name 'LesserClass' point to MyLesserClass.

Here's a simple example demonstrating the same by overriding __getattribute__:

classA:
    a = 'A.a'
    b = 'A.b'classB:
    deffunc_a(self):
        print(A.a)

    deffunc_b(self):
        print(A.b)


classC:
    a = 'C.a'
    b = 'C.b'classD(B):
    deffunc_a(self):
        print(C.a)

    def__getattribute__(self, attr):
        value = object.__getattribute__(self, attr)
        ifcallable(value):
            value = update_namespace(value, {'old': {'name': 'A', 'obj': A}, 'new': {'obj': C}})
        return value


defupdate_namespace(func, namespace):
    defwrapper(*args, **kwargs):
        # Update the globals
        func.__globals__[namespace['old']['name']] = namespace['new']['obj']
        val = func(*args, **kwargs)
        # Restore it back to the actual value
        func.__globals__[namespace['old']['name']] = namespace['old']['obj']
        return val
    return wrapper


d = D()
d.func_a()  # This should print C.a
d.func_b()  # This should print C.b

Output:

C.a
C.b

Post a Comment for "Override Used Classes In Parent Class"