Is it good practice to do a nested class in python?
I was able to define class A, use a list of instances of another class B as an instance variable of class A. class B has a function to change class A to another instance variable a1. Class A also has a function to change the instance variable of class B bb. Thus, class A can access class B and class B can access class A. The two classes are related to each other. I know we can make it easy to change the entire instance variable and function of class B to class A. But in my project, this nested structure is what is real.
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)
I want to know what if this type of nested class would decrease python's efficiency? Any better solution?
source to share
Class nesting does not decrease or improve execution efficiency. This can change the effectiveness of service and understanding.
Nested class because there is only one attribute of the parent class. You will need to reference it as A.B
, not B
. What is it, you have postponed the search to another namespace. In other words, your method __init__
will fail because the global name B
does not exist, only A.B
and exist self.B
(both refer to the same class object).
There is no relationship between a nested class and its parent, as in Java.
Most Python developers do not embed classes, so when you do, you are breaking the agreement and adding to the maintenance cost.
source to share