首页 > 解决方案 > 如何找出我通过 Child 调用 Child.parent_funcn 而不是通过 Parent 类?

问题描述

这是我想要实现的简单形式的示例。

class Parent:
     def abc():
         pass

class Child(Parent):
     def pqr():
         pass
    
Child.abc
<function Parent.abc()>

Child.abc.__qualname__
'Parent.abc'

figure_out_class_from_class_func(class_func):
   ...
   derive class from class_func.__qualname__
   return class

figure_out_class_from_class_func(Child.abc) returns -> Parent. 
Actually I want it to return Child as actually I am passing Child class.

所以基本上__qualname__不是我的朋友在这里。是否有可能使用 Class.function 找出实际类而不是父类(实现函数的地方)?

编辑:更好的例子:

class Parent():
     def __init__(self):
         print(self.x)
     def parent_func1(self):
         pass


class Child(Parent):
     x=1

     def __init__(self):
         print(self.x)

     def child_func1(self):
         pass



def special_function(class_func):
     func_module = inspect.getmodule(class_func)
     class_name = getattr(class_func, "__qualname__", None).split(".")[0]
     class_obj = getattr(func_module, class_name)
     class_obj()

Now calling special_function(Child.child_func1) is fine-> print 1

But special_function(Child.parent_func1) gives error:

ERROR:root:Internal Python error in the inspect module.
Below is the traceback from this internal error.

      1 class Parent():
      2      def __init__(self):
----> 3          print(self.x)
      4      def parent_func1(self):
      5          pass

AttributeError: 'Parent' object has no attribute 'x'

有什么办法可以找出我通过 Child 而不是通过 Parent 调用了 Child.parent_funcn ?

标签: pythonpython-3.xinheritance

解决方案


推荐阅读