简体   繁体   English

在isinstance中仅使用类名而不使用名称空间

[英]Use only class name without namespace in isinstance

This works in a script to recognise if a is of class myproject.aa.RefClass 这在脚本中起作用,以识别a是否属于myproject.aa.RefClass类。

isinstance(a, myproject.aa.RefClass)

But how could I do it so I do not have to specify the full namespace ? 但是我该怎么办,这样就不必指定完整的名称空间了? I would like to be able to type: 我希望能够输入:

isinstance(a, RefClass)

How is this done in Python ? 如何在Python中完成?

EDIT: let me give more details. 编辑:让我给更多的细节。

In module aa.referencedatatable.py: 在模块aa.referencedatatable.py中:

class ReferenceDataTable(object):
    def __init__(self, name):
        self.name = name

    def __call__(self, f):
        self._myfn = f
        return self

def referencedatatable_from_tag(tag):
    import definitions
    defn_lst = [definitions]
    for defn in defn_lst:
        referencedatatable_instance_lst = [getattr(defn, a) for a in dir(defn) if isinstance(getattr(defn, a), ReferenceDataTable)]
        for referencedatatable_instance in referencedatatable_instance_lst
            if referencedatatable_instance.name == tag
                return referencedatatable_instance
    raise("could not find")

def main()
    referencedata_from_tag("Example")

In module aa.definitions.py: 在模块aa.definitions.py中:

from aa.referencedatatable import ReferenceDataTable

@ReferenceDataTable("Example")
def EXAMPLE():
    raise NotImplementedError("not written")

For some reason calling the main from aa.referencedatatable.py will throw as it will not be able to recognise the instance of the class. 由于某种原因,从aa.referencedatatable.py调用main将会抛出,因为它将无法识别该类的实例。 But if I copy this main in another module it will work: 但是,如果我将此主目录复制到另一个模块中,它将起作用:

import aa.referencedatatable

a = aa.referencedatatable.referencedatatable_from_tag("Example")
print a

This second example works, for some reason calling this function inside the same module where the class is declared does not. 第二个示例有效,由于某种原因,在声明该类的同一模块内调用此函数无效。

The 'namespace' is just a module object, and so is the class. “命名空间”只是一个模块对象,类也是如此。 You can always assign the class to a different name: 您始终可以将类分配给其他名称:

RefClass = myproject.aa.RefClass

or better yet, import it directly into your own namespace: 或者更好的是,将其直接导入到您自己的名称空间中:

from myproject.aa import RefClass

Either way, now you have a global name RefClass that references the class object, so you can do: 无论哪种方式,现在都有一个引用类对象的全局名称RefClass ,因此可以执行以下操作:

isinstance(a, RefClass)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM