35

I managed to define a class A, use a list of instances of another class B as class A's instance variable. class B has a function to change class A's other instance variable a1. class A also has a function to change class B's instance variable bb. So class A can access class B and class B can access class A.

The two classes are nested together. I know we can make things easier to change all instance variables and functions of class B to class A. But in my project, this nested structure is the real way things are.

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)

What I want to know is if such kind of nested class will reduce the python efficiency? Any better solution?

Raed Ali
  • 390
  • 1
  • 4
  • 18
xibinke
  • 687
  • 2
  • 7
  • 11
  • 1
    You might want to read [the zen](https://www.python.org/dev/peps/pep-0020/). – Ami Tavory May 21 '15 at 14:08
  • Python's nested classes aren't like Java's where the nested class where the inner class can reference instances of the outer class. They're effectively two separate classes. `A.a1 = pyfunc1()` will assign the `a1` field on the _class_. – Colonel Thirty Two May 21 '15 at 14:08

1 Answers1

65

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.

mblakesley
  • 560
  • 2
  • 9
  • 17
Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
  • Thank you. I modified my script according to you suggestion. And I'll give up such kind of style hence. – xibinke May 21 '15 at 14:20