Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested class is not defined in itself

The following code successfully prints OK:

class B(object):
        def __init__(self):
            super(B, self).__init__()
            print 'OK'

class A(object):
    def __init__(self):
       self.B()

    B = B

A()

but the following which should work just as same as above one raises NameError: global name 'B' is not defined

class A(object):
    def __init__(self):
       self.B()

    class B(object):
        def __init__(self):
            super(B, self).__init__()
            print 'OK'
A()

why?

like image 379
mhsekhavat Avatar asked Oct 03 '22 04:10

mhsekhavat


1 Answers

B is available in the scope of A class - use A.B:

class A(object):
    def __init__(self):
       self.B()

    class B(object):
        def __init__(self):
            super(A.B, self).__init__()
            print 'OK'

A()

See documentation on Python Scopes and Namespaces.

like image 55
alecxe Avatar answered Oct 07 '22 18:10

alecxe