跳至主要内容

Python 内部类

在这篇基础 Python 教程中,您将了解为何以及何时应该使用内部类。
· 5分钟 阅读

使用 AI 探索

您可能听说过 Python 中的嵌套函数。如果您理解这个概念,那么理解内部/嵌套类就不难了。我们将在这里探索一些关于内部或嵌套类的新内容。

1. 内部类或嵌套类

内部类或嵌套类定义在另一个类的内部。请看内部或嵌套类的结构。

## outer class
class Outer:

    ## inner class
    class Inner:
        pass

        ## multilevel inner class
        class InnerInner:
            pass

    ## another inner class
    class _Inner:
        pass

    ## ...

    pass

在线运行和编辑此教程中的代码

运行代码

2. 为什么使用内部类?

  1. 将两个或更多类进行分组。假设您有两个类 Car 和 Engine。每辆Car 都需要一个 Engine。但是,Engine 离开 Car 又不会单独使用。因此,您可以把 Engine 作为 Car 的内部类。这样可以帮助精简代码。

  2. 隐藏实现也是嵌套类的一个用途。您可以将嵌套类对外部世界隐藏。

  3. 更易于理解这些类。这里的类关系紧密。您不必在代码中到处查找相关类,它们都在一起。

内部或嵌套类并非 Python 中最常用的特性。但它可以是实现代码的一个不错选择。使用内部或嵌套类时,代码更容易组织。

3. 编写内部类

实现内部或嵌套类并不困难。您可以在此处查看代码结构。

您可以在外部类中使用 self 关键字访问内部类。这样,您就能在外部类中快速创建内部类的实例并按需操作。不过,您无法在内部类中访问外部类。下面看一个示例。

class Outer:
    """Outer Class"""

    def __init__(self):
        ## instantiating the 'Inner' class
        self.inner = self.Inner()

    def reveal(self):
        ## calling the 'Inner' class function display
        self.inner.inner_display("Calling Inner class function from Outer class")

    class Inner:
        """Inner Class"""

        def inner_display(self, msg):
            print(msg)

现在,您将创建 Outer 类的实例,并调用它的 reveal() 方法来执行 Inner 类的方法 inner_display()。

## creating an instance of the 'Outer' class
outer = Outer()
## calling the 'reveal()' method
outer.reveal()
Calling Inner class function from Outer class

我们再来看另一种访问内部类的方式。这种方式稍微没那么高效。

Outer().Inner().inner_display("Calling the Inner class method directly")
Calling the Inner class method directly

如果您想在外部类之外创建内部类的实例怎么办?可以吗?可以的。来看如何在外部类之外创建内部类的实例。

outer = Outer()

## instantiating the inner class
inner = outer.Inner() ## inner = Outer().Inner() or inner = outer.inner
inner.inner_display("Just Print It!")
Just Print It!

3.1. 多个内部类

这是指一个类中包含多个内部类。您可以在同一个类中定义多个内部类。正如我们之前所示,实现多个内部类也很容易。

class Outer:
    """Outer Class"""

    def __init__(self):
        ## Instantiating the 'Inner' class
        self.inner = self.Inner()
        ## Instantiating the '_Inner' class
        self._inner = self._Inner()

    def show_classes(self):
        print("This is Outer class")
        print(inner)
        print(_inner)

    class Inner:
        """First Inner Class"""

        def inner_display(self, msg):
            print("This is Inner class")
            print(msg)

    class _Inner:
        """Second Inner Class"""

        def inner_display(self, msg):
            print("This is _Inner class")
            print(msg)

    ## ...

访问这些类与我们之前的做法相同。请看示例以便更好理解。

## instantiating the classes

## 'Outer' class
outer = Outer()
## 'Inner' class
inner = outer.Inner() ## inner = outer.inner or inner = Outer().Inner()
## '_Inner' class
_inner = outer._Inner() ## _inner = outer._outer or _inner = Outer()._Inner()

## calling the methods
outer.show_classes()

print()

## 'Inner' class
inner.inner_display("Just Print It!")

print()

## '_Inner' class
_inner.inner_display("Just Show It!")
This is Outer class
<__main__.Outer.Inner object at 0x0000021B37962048>
<__main__.Outer._Inner object at 0x0000021B37962160>

This is Inner class
Just Print It!

This is _Inner class
Just Show It!

3.2. 多级内部类

在多级内部类中,内部类中还包含另一个类,而这个类相对于前一个类来说也是内部类。您可以在此处查看这一层级结构:

class Outer:
    """Outer Class"""

    def __init__(self):
        ## instantiating the 'Inner' class
        self.inner = self.Inner()
        ## instantiating the multilevel 'InnerInner' class
        self.innerinner = self.inner.InnerInner()

    def show_classes(self):
        print("This is Outer class")
        print(inner)

    ## inner class
    class Inner:
        """First Inner Class"""

        def __init__(self):
            ## instantiating the 'InnerInner' class
            self.innerinner = self.InnerInner()

        def show_classes(self):
            print("This is Inner class")
            print(self.innerinner)

        ## multilevel inner class
        class InnerInner:

            def inner_display(self, msg):
                print("This is multilevel InnerInner class")
                print(msg)

        def inner_display(self, msg):
            print("This is Inner class")
            print(msg)

    ## ...

让我们看看如何实例化多级内部类。

outer = Outer()

inner = outer.Inner()

## this is 'InnerInner' class instance
innerinner = inner.InnerInner() ## innerinner = Outer().Inner().InnerInner()

## let's call its method inner_display
innerinner.inner_display("Just Print It!")
This is multilevel InnerInner class
Just Print It!

总结

希望您现在已经理解了内部类的概念。现在是时候亲自尝试嵌套类了。祝编码愉快 :)

如果您想进一步学习类,请查看 DataCamp 的 Python 面向对象编程(OOP):教程。

参加 DataCamp 的 Object-Oriented Programming in Python 课程。

主题