本文介绍了为什么我们需要__init__来初始化python类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是OOP的新手,我需要一些帮助来了解python类中对构造函数的需求。

I'm pretty new to OOP and I need some help understanding the need for a constructor in a python class.

我了解 init 用于初始化类变量,如下所示:

I understand init is used to initialize class variables like below:

class myClass():
    def __init__ (self):
        self.x = 3
        print("object created")

A = myClass()
print(A.x)
A.x = 6
print(A.x)

输出:

object created
3
6

但是,我也可以这样做,

but, I could also just do,

class myClass():
    x = 3
    print("object created")

A = myClass()
print(A.x)
A.x = 6
print(A.x)

打印出相同的结果。

请您解释一下为什么我们需要一个

Could you please explain why we need a constructor or give me an example of a case when the above method will not work?

推荐答案

引文:但是我还可做

class myClass():
    x = 3
    print("object created")

A = myClass()
print(A.x)
A.x = 6
print(A.x)

不行。一旦要创建两个或多个相同类的对象,就存在根本的区别。也许这样的行为变得更清楚

No you cannot. There is a fundamental difference once you want to create two or more objects of the same class. Maybe this behaviour becomes clearer like this

class MyClass:
    x = 3
    print("Created!")

a = MyClass() # Will output "Created!"
a = MyClass() # Will output nothing since the class already exists!

原则上,您需要__init__来编写该代码,该代码需要在每个新对象初始化时为每个新对象执行/创建-读完类后不仅一次。

In principle you need __init__ in order to write that code that needs to get executed for every new object whenever this object gets initialized / created - not just once when the class is read in.

这篇关于为什么我们需要__init__来初始化python类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 08:00