python - 如何找出我通过 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 ?
解决方案
推荐阅读
- python - 更有效地读取 CVS 文件列标题
- javascript - Redux 有一个数组但不能映射数据
- python - LeftAnti 加入 pyspark 太慢了
- javascript - Fullcalendar v5 eventContent 不适用于 Angular js
- c# - Xapi 不适用于 Android 设备,但适用于 Unity 编辑器
- python - 原始 9-D0F IMU 值(陀螺仪、加速度计、磁力计)的 Yaw-Pitch-Roll 转换公式
- javascript - 为什么我给变量加 1 但每次都加“2”?
- html - 最大高度在 Safari 中无法正常工作
- elasticsearch - 向 values.yml 添加额外值时,Elasticsearch helm 部署错误提示 crashloopback
- arrays - 使用 vue.js 将二维关联数组转换为 Object