python namespace: __main__.Class not isinstance of package.Class

前端 未结 3 2099
轮回少年
轮回少年 2021-01-12 08:41

Consider you have two python files as defined below. Say one is a general package (class2), and the other one does specific overrides and serves as the executab

3条回答
  •  花落未央
    2021-01-12 09:04

    You could use the type() function (you'll find this invocation fairly common, in fact!):

    #!/usr/bin/python
    class Test(object):
        pass
    
    class Verificator():
        def check(self, myObject):
            if not isinstance( type(myObject), type(Test) ):
                print "%s is no instance of %s" % (type(myObject),Test)
            else:
                print "OK!"
    
    if __name__ == '__main__':
        from class2 import getTest
    
        v = Verificator()
        t = Test()
        v.check(t)
        s = getTest()
        v.check(s)
    

    The perhaps worse solution:

    if not isinstance( myObject.__class__, Test.__class__ ):  # Use __class__ here.
    

    They're of course equivalent, but it's considered bad form to need to use double-underscore members unless you desperately need to! It's worth knowing of their existence, though, hence why I've included this one in my answer.

    Note that this happens, to the best of my knowledge, because when you run python class1.py, class1.py would have no module. As such, python places everything into the __main__ module for you. This isn't the case when you import it from any other script, so seeing something as part of the __main__ module is actually the special case!

提交回复
热议问题