What are the consequences of nesting classes?

Question:

I have this example code, with a class B nested inside class A:

class A:
    class B:
        count = 0
        def __init__(self,b1=None,b2=None):
            self.b1 = b1
            self.b2 = b2
        def funcb(self,bb):
            A.a1 = pyfunc1(bb)
    def __init__(self,a1,a2):
        self.a1 = a1
        self.a2 = a2
        self.listb = [A.B()]
    def funca(self,aa):
        A.B.count += 1
        b = A.B(self.a1,self.a2)
        listb.append(b)
        listb[A.B.count].b1 = listb[A.B.count-1].b1.pyfunc2(aa)
        listb[A.B.count].b2 = pyfunc3(aa,self.a2)
        listb[A.B.count].funcb(self.a2)

Here, the A class maintains a list of instances of the nested B class. B provides functionality to change A‘s other instance variable a1, while A has a function to change B‘s instance variable bb. Which is to say, these classes can access each other.

Will nesting classes like this reduce the efficiency of the code? How else can I solve the problem?

Asked By: xibinke

||

Answers:

Nesting a class doesn’t reduce nor increase execution efficiency. It may alter maintenance and understanding efficiency.

The nested class becomes just another attribute on the parent class. You’ll have to reference it as A.B rather than B. That’s it, you deferred the lookup to a different namespace. In other words, your __init__ method will fail, because there is no global name B, only A.B and self.B exist (both referencing the same class object).

There is otherwise no special relationship between a nested class and their parent, as there is in Java.

Most Python developers do not nest classes, so when you do so you break convention and increase maintenance cost.

Answered By: Martijn Pieters
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.