对def __init__内部的__init__方法感到困惑 [英] confused about __init__ method inside of def __init__
问题描述
在以下代码中:
import tkinter as tk
class CardShuffling(tk.Tk):
background_colour = '#D3D3D3'
deck_size = 52
def __init__(self):
tk.Tk.__init__(self) # What does this do?
我对最后一行的目的感到困惑.CardShuffling实例从tk.Tk
继承,不是最后一行只是重复CardShuffling(tk.Tk)
已经处理的内容?
I am confused about the purpose of the last line.. an instance of CardShuffling inherits from tk.Tk
, doesn't the last line just repeat what is already taken care of by CardShuffling(tk.Tk)
??
推荐答案
CardShuffling(tk.Tk)
仅使类CardShuffling
成为tk.Tk
的子级.您的新类继承了该类的所有方法.
CardShuffling(tk.Tk)
only makes the class CardShuffling
a child of tk.Tk
. your new class inherits all the methods of this class.
但是,如果您创建一个新对象,则仍然必须调用该基类的构造函数(以新对象作为参数).想象在父类的构造函数中有一行self.a = 0
.初始化新实例时,您的子类必须运行此行; CardShuffling(tk.Tk)
不能为您做到这一点;您需要运行父类的__init__
.
but if you create a new object you still have to call the constructor of that base class (with the new object as argument). imagine there is a line self.a = 0
in the constructor of the parent class. your child class has to run this line when you initialize a new instance; CardShuffling(tk.Tk)
can not do that for you; you need to run __init__
of the parent class.
在python 3中执行此操作的通常方法是
the usual way to do that in python 3 is
def __init__(self):
super().__init__()
在这种情况下与
def __init__(self):
tk.Tk.__init__(self)
maybe this article on inheritance helps and there is even a book chapter freely available.
这篇关于对def __init__内部的__init__方法感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!