嵌套类是一个好习惯吗? [英] Is it a good practice to nest classes?

查看:36
本文介绍了嵌套类是一个好习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设法定义了一个类 A,使用另一个类 B 的实例列表作为类 A 的实例变量.class B 有一个函数可以改变 class A 的另一个实例变量 a1.A 类也有一个函数来改变B 类的实例变量bb.所以A类可以访问B类,B类可以访问A类.

I managed 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 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.

两个类嵌套在一起.我知道我们可以更轻松地将 B 类的所有实例变量和函数更改为 A 类.但在我的项目中,这种嵌套结构才是真实的.

The two classed 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)

我想知道这样的嵌套类是否会降低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,只有 ABself.B 存在(都引用同一个类对象).

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).

嵌套类与其父类之间没有其他特殊关系,就像在 Java 中那样.

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

大多数 Python 开发人员不嵌套类,因此这样做会破坏约定并增加维护成本.

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

这篇关于嵌套类是一个好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆