python - PySide 中的 __init__ 方法

标签 python

在一些教程中,我读到对于 __init__ 方法,我必须执行以下操作:

class App:
    def __init__(self):
    ...

但是,在 PySide 中我发现了这个。 QWidget.__init__(self) 行有什么作用以及我需要它吗?

class App(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        ...

最佳答案

调用cls.__init__(self)(其中cls可以是任何类),将简单地调用cls self 上的 __init__。这是一个例子:

class Foo(object):
    def __init__(self):
        self.foo = True
        print('Initializing object {} on Foo.__init__!'.format(self))

class Bar(object):
    def __init__(self):
        Foo.__init__(self)
        self.bar = True
        print('Initializing object {} on Bar.__init__!'.format(self))

现在创建 Bar 的实例将输出两个 __init__:

>>> b = Bar()
Initializing object <__main__.Bar object at 0x00000000039329E8> on Foo.__init__!
Initializing object <__main__.Bar object at 0x00000000039329E8> on Bar.__init__!

此外,b 现在具有两个属性:foobar

<小时/>

您应该很少调用其他类的__init__,除非您要子类化其他类。上面的示例通常是不正确的,因为 Bar 不是 Foo 的子类。

即使您对某个类进行子类化,也不应该直接使用其名称来访问该类,而应使用 Python 的内置函数 super():

# "WRONG"  (usually)
class X(Y):
    def __init__(self):
        Y.__init__(self)

# RIGHT
class X(Y):
    def __init__(self):
        super().__init__()  # self is omitted when using super()

关于python - PySide 中的 __init__ 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31515585/

相关文章:

python - Bigquery Python API 按特定字段创建分区表

python - 无法使用 Mosquitto/Paho for Python 接收超过 20 条 MQTT 消息

python - 无法使用 Windows 命令提示符创建 Django 项目

python - 图像到 numpy 数组到图像,最后再次到数组导致错误的数组

python - 如何仅初始化一次数据库连接并在 python 运行时重用它?

python - 使用迭代将旧字典中的值提取到新字典中

python - OpenCV-Python : Find a code for writing keypoins to a file

python - 设置 Python 的 collections.defaultdict 的默认字符串值

python - 以日期或其他类型值的特定交替间隔在绘图上设置背景颜色

python - django-registration 无法为身份验证电子邮件设置 "from"电子邮件地址