Python 中的嵌套类
    
    Manav Narula
    2021年2月7日
    
    Python
    Python Class
    
 
类包含不同的数据成员和函数,并允许我们创建对象来访问这些成员。
Python 作为一种面向对象的编程语言,有很多这样的不同类的对象。在 Python 中,我们有一个重要的构造函数,叫做 __init__,每次创建类的实例时都会调用它,我们还有 self 关键字来引用类的当前实例。
嵌套类(也叫内类)是在另一个类中定义的。它在所有面向对象的编程语言中都是非常常用的,可以有很多好处。它并不能提高执行时间,但可以通过将相关的类归为一组来帮助程序的可读性和维护,而且还可以将嵌套类隐藏起来,不让外界看到。
下面的代码展示了一个非常简单的嵌套类的结构。
class Dept:
    def __init__(self, dname):
        self.dname = dname
    class Prof:
        def __init__(self, pname):
            self.pname = pname
math = Dept("Mathematics")
mathprof = Dept.Prof("Mark")
print(math.dname)
print(mathprof.pname)
输出:
Mathematics
Mark
注意,我们不能直接访问内部类。我们使用 outer.inner 格式创建其对象。
我们可以访问外类中的嵌套类,但不能反过来访问。要访问外类中的嵌套类,我们可以使用 outer.inner 格式或 self 关键字。
在下面的代码中,我们对上述类做了一些改动,并使用父类访问嵌套类的一个函数。
class Dept:
    def __init__(self, dname):
        self.dname = dname
        self.inner = self.Prof()
    def outer_disp(self):
        self.inner.inner_disp(self.dname)
    class Prof:
        def inner_disp(self, details):
            print(details, "From Inner Class")
math = Dept("Mathematics")
math.outer_disp()
输出:
Mathematics From Inner Class
在 Python 中,我们也可以有多个嵌套类。这种情况称为多嵌套类,有一个或多个内类。
也可以有一些情况,我们在一个嵌套类中有一个嵌套类,这种情况称为多级嵌套类。
下面的代码展示了一个非常简单的多级嵌套类的例子。
class Dept:
    def __init__(self, dname):
        self.dname = dname
    class Prof:
        def __init__(self, pname):
            self.pname = pname
        class Country:
            def __init__(self, cname):
                self.cname = cname
math = Dept("Mathematics")
mathprof = Dept.Prof("Mark")
country = Dept.Prof.Country("UK")
print(math.dname, mathprof.pname, country.cname)
输出:
Mathematics Mark UK
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
    
作者: Manav Narula
    Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.
LinkedIn