Greg Brown
Greg Brown

Reputation: 1299

Scope of classes inside of functions and classes inside of a class in python

I am writing some code and had a general question about python

If I have something like this:

class A():
       def __init__(self):
           self.name
           ...
       def doSomething(self):
           class B():
               def __init__(self):
                   self.name
                   ...
           c = B()
           c.whatever()

Does that mean that class B is private to that function only or can it be called from an instance of class A? On that note if I had some code like this:

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

    def __init__(self):
        self.name
        ...
        def doSomething(self):
        ...       

I can call it by doing this d = A.B() right?

Upvotes: 0

Views: 52

Answers (1)

BrenBarn
BrenBarn

Reputation: 251373

The thing to realize is that the class statement just creates a variable whose value is a class. The way the resulting class's scope works is the same the way a variable's scope would work if you just did a normal variable assignment like x = 2.

Any variables you create inside a function are local to that function unless you specify otherwise. So using a class statement inside a function just creates a local variable whose value is a class. It can't be accessed from outside the function.

In other words, this:

def foo():
    class A(object):
        pass

is not really different from this:

def foo():
    A = 2

In both cases you create a local variable A inside the function. In one case its value is a class and in the other its value is an integer, but in both cases it's a local variable and has no existence outside the function.

In your second example, the class is created inside the enclosing class. Variables created inside a class namespace are class attributes, so yes, you can access it as you describe. (Why you'd want to do this is another question.) In other words, as above, this:

class A(object):
    class B(object):
        pass

is not that different from this:

class A(object):
    B = 2

In both cases you create a class A that has a class attribute B.

Upvotes: 1

Related Questions