您的位置:首页技术文章
文章详情页

Python中的__init__作用是什么

【字号: 日期:2022-07-21 18:03:42浏览:3作者:猪猪

看到Python中有个函数名比较奇特,__init__我知道加下划线的函数会自动运行,但是不知道它存在的具体意义..

Python中所有的类成员(包括数据成员)都是 公共的 ,所有的方法都是 有效的 。

只有一个例外:如果你使用的数据成员名称以 双下划线前缀 比如__privatevar,Python的名称管理体系会有效地把它作为私有变量。

这样就有一个惯例,如果某个变量只想在类或对象中使用,就应该以单下划线前缀。而其他的名称都将作为公共的,可以被其他类/对象使用。记住这只是一个惯例,并不是Python所要求的(与双下划线前缀不同)。

同样,注意__del__方法与 destructor 的概念类似。'

恍然大悟原来__init__在类中被用做构造函数,固定写法,看似很死板,其实有道理

def __init__(self, name): ’’’Initializes the person’s data.’’’ self.name = name print ’(Initializing %s)’ % self.name # When this person is created, he/she # adds to the population Person.population += 1

name变量属于对象(它使用self赋值)因此是对象的变量

self.name的值根据每个对象指定,这表明了它作为对象的变量的本质。

例如我们定义一个Box类,有width, height, depth三个属性,以及计算体积的方法:

class Box: def setDimension(self, width, height, depth): self.width = width self.height = height self.depth = depth def getVolume(self): return self.width * self.height * self.depthb = Box()b.setDimension(10, 20, 30)print(b.getVolume())

我们在Box类中定义了setDimension方法去设定该Box的属性,这样过于繁琐,而用__init__()这个特殊的方法就可以方便地自己对类的属性进行定义,__init__()方法又被称为构造器(constructor)

class Box: #def setDimension(self, width, height, depth): # self.width = width # self.height = height # self.depth = depth def __init__(self, width, height, depth): self.width = width self.height = height self.depth = depth def getVolume(self): return self.width * self.height * self.depthb = Box(10, 20, 30)print(b.getVolume())

知识点扩展:

__init__()要点如下:

1.名称固定,必须为__init__()

2.第一个参数固定,必须为self。self指的就是刚刚创建好的示例对象。

3.构造函数通常用来初始化示例属性,如下代码就是初始化示例属性:

4.通过类名(参数列表),来调用构造函数,调用后,将创建好的对象返回给相应的变量。

5.__init__()方法:初始化创建好的对象,初始化指的是:'给实例属性赋值'

6.__new__()方法:用于创建对象,但我们一般无需定义该方法。

以上就是Python中的__init__作用是什么的详细内容,更多关于Python中的__init__到底是干什么的的资料请关注好吧啦网其它相关文章!

标签: Python 编程
相关文章: