Python中类的def __init__(self, *args, **kwargs)初始化

2024-05-15 15:27:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python还不熟悉。我在一个正在开发的OpenFlow控制器中遇到了Python代码。

class SimpleSwitch(app_manager.RyuApp):
    OFP_VERSIONS = [ofproto_v1_0.OFP_VERSION]

    def __init__(self, *args, **kwargs):
        super(SimpleSwitch, self).__init__(*args, **kwargs)
        self.mac_to_port = {}

我的问题如下。

  1. __init__是类的构造函数吗?

  2. 是{c*2}}与C++的^ {< CD3>}指针相同吗?

  3. super(SimpleSwitch, self).__init__(*args, **kwargs)是否意味着调用父/超类的构造函数?

  4. 能否将新成员作为mac_to_port添加到self中?或者已经添加了并且刚刚在这里初始化?


Tags: to代码selfappinitportmacargs
2条回答
  1. __init__是初始化器;__new__是构造函数。参见例如this question
  2. 实际上是的:Python中实例方法的第一个参数,按照惯例称为self,是实例本身。
  3. 调用父类的初始化器,是的。
  4. 除了父类已有的属性之外,它还向SimpleSwitch添加了一个新属性,一个空字典。
  1. Super in Python is not like C++'s super. I have not used C++, but I can tell you that super in python does not act the same. Instead of calling the parent, python super calls the children of the class in which super is called, then moves in an interesting chain. Think of three tiered class system where there is a single base class, two subclasses to that base class, and two subclasses to those subclasses. Calling super on the bottom tier would call the parent immediately above it, but calling super in one of the second-tier classes would call their children first, then it looks to the side and calls the other classes on it's own tier, then the children of that same-tier class are called. Once all of the same-tier classes and all of their children re called, then super calls the parent of the middle-tier classes.

很难用语言解释。观看雷蒙德·赫廷格在皮孔的“超级超人”演讲。他很好地解释了它是如何工作的,以及为什么python的super不应该被称为“super”。

相关问题 更多 >