在模块美孚我有一个函数:Pydev的/日食:不能识别动态创建的类
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.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的带有红叉说:“从进口未定义的变量:球”抱怨。
这是可以预料的。问题是我要在我的代码中注册很多“方案”,导致错误消息到处都是。我想这不会造成可怕的后果,但那会非常烦人。
有没有人有解决方案?
编辑
这里是我的解决方案,这并不完全符合我想要的东西,但足够接近
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.register_scheme("ball",color,distance)
my_ball = foo.create("ball",color="red",distance=0.5)
谢谢!这个解决方案并不是我所需要的,因为Ball只存在于当前的包中。这个想法是有不同的模块,可以花费Schemes库... – Vince
>我需要什么,因为Ball只存在于当前包<我的解决方案完全是这样。当你做'Ball = foo.create_scheme(“ball”,color,distance)'时,在当前模块中创建一个名为'Ball'的变量。如果你的模块叫做'bar',那么会出现'bar.Ball'类。 – warvariuc
对不起,错过了。感谢您的解决方案! – Vince