python - 使用反射窥探模块及其类

标签 python dynamic

我遇到了一个有点难以解释的问题。我有一个包含多个类的模块:someModule.py

#imports over here
class Default(Base):
 def __init__(self):
   a = Rectangle() #all these guys derive from Shape
   b = Circle()
   c = Sphere()

class Foo:
 #members over here

#other classes/functions/whatever we can define here, except the boiler plate code to check __main__

我想做的是在运行时创建一个派生自特定基类(例如 Base)的类的对象,并操作那些派生自另一个特定基类(例如 Shape)的数据成员。意思是我想编写这样一个采用模块名称并执行上述任务的脚本。我有什么想法可以使用检查或其他方法来做到这一点吗?我看了一下 inspect,但没有完全找到应该完成工作的方法。我可能遗漏了一些东西。

最佳答案

在创建实例之前,无法知道 __init__ 中的内容。

您只能在之后检查它们,一种方法是使用 vars() :

defy = Default()
for name,value in vars(defy).items():
    if isinstance(value, Shape):
        # manipulate

要对 someModule.py 中所有也是 Base 子类的类执行上述操作:

import someModule

instances = []
for cls_name,cls in vars(someModule):
    if issubclass(cls, Base):
        obj = cls()
        for name,value in vars(cls).items():
            if isinstance(value, Shape):
                # manipulate
        instances.append(obj)

相反,如果您想操作哪个 Shape 子类将被实例化,您必须将它们设为类属性,例如:

class Default(Base):
    default_shapes = [Rectangle, Circle, Sphere]
    def __init__(self):
        self.shapes = [shape() for shape in self.__class__.default_shapes]

关于python - 使用反射窥探模块及其类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9147332/

相关文章:

python - 在numpy中找到两个多边形之间的距离

python - 使用 2 位数字与 3 位数字时,django 中的数学结果不正确?

python - 为什么我的按钮没有转到 GUI 窗口的最右侧?

c# - 将 XML 项动态添加到列表框时出现问题,C#?

jquery - 使用 jQuery 查找类并添加属性

c++ - 用于分析 bool vector 的 vector 的动态规划

javascript 使用独特的 onclick 事件创建 div

编辑字典列表的 Pythonic 方式

python - networkx shortest_path(G[, source, target, weight]) 函数的源算法

jquery - 用jQuery计算Children的总宽度