Python: isinstance() undefined global name

2019-08-18 02:02发布

I'm new with Python and I'm trying to use classes to program using objects as I do with C++.

I wrote 3 .py files.

a.py

from b import *

class A:
    def __init__(self):
        self.m_tName = "A"

    def test(self):
        tB = B()

        tB.do( self )

b.py

from a import *

class B:
    def __init__(self):
        self.m_tName = "B"

    def do(self, tA ):
        if not isinstance( tA, A ):
            print ( "invalid parameter" )

        print( "OK" )

demo.py:

from a import *

if __name__ == "__main__":
    tA = A()

    tA.test()

As you can see I want to use a A() object to call the member function test() that creates a B() object and call the member function do() that uses a A() object.

So in B::do() I want to check the parameters using the built-in function isinstance(). But python tells me that there's a NameError: global name 'A' is not defined.

The A() class file is imported at the top of the b.py file.

Does anyone know what I'm doing wrong here ?

标签: python oop
2条回答
手持菜刀,她持情操
2楼-- · 2019-08-18 02:20

You have a circular dependancy, a.py and b.py import each other.

You could move either import statement inside the method where it is used. So b.py would become:

class A:
    def __init__(self):
        self.m_tName = "A"

    def test(self):
        from b import B
        tB = B()

        tB.do( self )
查看更多
我想做一个坏孩纸
3楼-- · 2019-08-18 02:34

As pointed in some comment, circular dependencies are not well handled if imported in the form from a import A.

In short, the problem with ... import * is that is causes the local scope to have all its declarations overridden, in effect making the identification of from which module (in your case) a class comes from. This causes exactly what you are facing.

Changing the import statement in the following way, together with a classified reference to a.A, produces OK as output.

import a

class B:
    def __init__(self):
        self.m_tName = "B"

    def do(self, tA ):
        print tA
        if not isinstance( tA, a.A ):
            print ( "invalid parameter" )

        print( "OK" )

As a bit of additional information, this has already been discussed in Why is "import *" bad?. I would point in special to this answer: https://stackoverflow.com/a/2454460/1540197.

**Edit:**This article explain the import confusion.

查看更多
登录 后发表回答