Python Pydev/eclipse:无法识别动态创建的类
在模块Foo中,我有一个函数:Python Pydev/eclipse:无法识别动态创建的类,python,eclipse,class,dynamic,pydev,Python,Eclipse,Class,Dynamic,Pydev,在模块Foo中,我有一个函数: def register_scheme(class_name,*properties_class): scheme_class = type(class_name, (Scheme,), dict( _properties_classes={c.__name__:c for c in properties_class} )) # Scheme is another class defined in Foo globals()[class_name]
def register_scheme(class_name,*properties_class):
scheme_class = type(class_name, (Scheme,), dict( _properties_classes={c.__name__:c for c in properties_class} )) # Scheme is another class defined in Foo
globals()[class_name] = scheme_class
在导入Foo的另一个模块中,我执行以下操作:
foo.register_scheme("ball",color,distance) # color and distance are two classes defined in this module
现在我可以做到:
ball = foo.ball("color"=red,"distance"=0.5) # __init__ function of Scheme takes care of this, code not shown
代码运行良好,但pydev抱怨红十字会说“import:ball中的未定义变量”
这是意料之中的。问题是我将在代码中注册大量的“scheme”,导致到处都是错误消息。我想这不会有可怕的后果,但那真的很烦人
有人会有解决办法吗
编辑 这是我的解决方案,它并不完全符合我想要的,但足够接近
def register_scheme(class_name,*properties_class):
#here some code checking if this class name is ok, removed for brevity #
scheme_class = type(class_name, (Scheme,), dict( _properties_classes={c.__name__:c for c in properties_class} ))
Scheme._known_scheme_classes[class_name]=scheme_class # _known_scheme_classes is a class dict of Scheme
def create(scheme_class_name,**values):
# some code checking such class has been registered, removed for brevity #
return Scheme._known_scheme_classes[scheme_class_name](**values)
现在我可以在导入foo的其他模块中执行此操作:
foo.register_scheme("ball",color,distance)
my_ball = foo.create("ball",color="red",distance=0.5)
Python是一种动态语言,因此静态代码分析器无法对所有内容进行内省 在您的情况下,PyDev抱怨
foo.ball
是一个“未定义的变量”是完全正常的,因为它ball
没有在foo
模块中定义,而是在运行时创建的。如果没有实际运行程序,Eclipse不会也不可能知道这一点
一般来说,拥有这种魔法是个坏主意
您的代码中包含以下内容:
globals()[class_name] = scheme_class
因此,您正在动态创建一个类,而无需验证它是否已经创建,然后将其注入到全局文件中
然后,我建议您不要注射,而是将其退回:
def crate_scheme(class_name, *properties_class):
scheme_class = type(class_name, (Scheme,), dict( _properties_classes={c.__name__:c for c in properties_class} )) # Scheme is another class defined in Foo
return scheme_class
然后在另一个模块中执行:
Ball = foo.create_scheme("ball", color, distance) # color and distance are two classes defined in this module
ball = Ball("color"=red, "distance"=0.5) # __init__ function of Scheme takes care of this, code not shown
这应该有助于消除PyDev的抱怨,但无论如何,如果可能的话,应该避免动态创建类:显式优于隐式(import This
)
在这里使用合成而不是继承。谢谢!这个解决方案并不是我真正需要的,因为Ball只存在于当前包中。我们的想法是使用不同的模块来扩展方案库…>我需要的是Ball只存在于当前包中<我的解决方案正是这样做的。执行Ball=foo.create_scheme(“Ball”、颜色、距离)
时,将在当前模块中创建一个名为Ball
的变量。如果您的模块被称为bar
,则会出现bar.Ball
class。