在Python中做嵌套类是一个很好的做法吗? [英] Is it a good practice to make nested class in python?
问题描述
我设法定义一个类A,使用另一个类B的实例列表作为类A的实例变量。类B具有改变类A的另一个实例变量a1的功能。 A类也有一个函数来改变B类的实例变量bb。因此,类A可以访问类B,类B可以访问类A.
两个类被嵌套在一起。我知道我们可以让事情更容易将所有的实例变量和类B的功能更改为类A.但在我的项目中,这个嵌套的结构是真正的东西。
I manage to define a class A, use a list of instance of another class B as class A's instance variable. class B has a function to change class A's another 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 classed are nested together. I know we can make things easier to change all instance variable and function of class B to class A. But in my project, this nested structure is what real 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)
我想知道的是,如果这样的嵌套类会减少python效率?任何更好的解决方案?
What I want to know is that if such kind of nested class will reduce the python efficiency? Any better solution?
推荐答案
嵌套类不会减少也不会提高执行效率。这可能会改变维护和理解效率。
Nesting a class doesn't reduce nor increase execution efficiency. It may alter maintenance and understanding efficiency.
嵌套类,因为只是父类的另一个属性。您必须以 A.B
而不是 B
的形式引用它。就是这样,你将查找推迟到不同的命名空间。换句话说, __ init __
方法将失败,因为没有全局名称 B
,只有 AB
和 self.B
存在(都引用同一个类对象)。
The nested class because 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).
大多数Python开发人员不会嵌套类,因此当你这么做时,嵌套类与其父类之间没有特殊的关系打破常规并增加维护成本。
Most Python developers do not nest classes, so when you do so you break convention and increase maintenance cost.
这篇关于在Python中做嵌套类是一个很好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!