这是一个简单的示例,它通过覆盖 __getattribute__ :class A: a = 'A.a' b = 'A.b'class B: def func_a(self): print(A.a) def func_b(self): print(A.b)class C: a = 'C.a' b = 'C.b'class D(B): def func_a(self): print(C.a) def __getattribute__(self, attr): value = object.__getattribute__(self, attr) if callable(value): value = update_namespace(value, {'old': {'name': 'A', 'obj': A}, 'new': {'obj': C}}) return valuedef update_namespace(func, namespace): def wrapper(*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 wrapperd = D()d.func_a() # This should print C.ad.func_b() # This should print C.b 输出: C.aC.bSuppose there is a class NiceClass using some other class LesserClass in a place I can't edit# NiceClass.pyclass LesserClass: ... # stuff ...class NiceClass: ... # Lots of use of lesser class in here... ...Now I want to use my own class MyLesserClass instead of LesserClass everywhere in an inherited version of NiceClass# MyNiceClass.pyfrom NiceClass import NiceClassfrom NiceClass import LesserClass as oldLesserClassclass LesserClass(oldLesserClass): ... # Some extra stuff ...class MyNiceClass(NiceClass): ... # Everywhere LesserClass was used I now want to use MyLesserClass ...But all the non-overridden methods in MyNiceClass will use the LesserClass from the old NiceClass.py.Everything would work as I want if I just copy-pasted in the whole definition of NiceClass into MyNiceClass.py.It's like I just want to inherit the source code and not the whole namespace. Maybe inheritence is the wrong way? 解决方案 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__:class A: a = 'A.a' b = 'A.b'class B: def func_a(self): print(A.a) def func_b(self): print(A.b)class C: a = 'C.a' b = 'C.b'class D(B): def func_a(self): print(C.a) def __getattribute__(self, attr): value = object.__getattribute__(self, attr) if callable(value): value = update_namespace(value, {'old': {'name': 'A', 'obj': A}, 'new': {'obj': C}}) return valuedef update_namespace(func, namespace): def wrapper(*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 wrapperd = D()d.func_a() # This should print C.ad.func_b() # This should print C.bOutput:C.aC.b 这篇关于覆盖父类中使用过的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-19 18:17