品易云推流 关闭
文章详情页
文章 > Python常见问题 > Python中的__init__到底是干什么的?

Python中的__init__到底是干什么的?

头像

silencement

2019-07-18 13:31:573074浏览 · 0收藏 · 0评论

看到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.depth
 
b = 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.depth
 
b = Box(10, 20, 30)
print(b.getVolume())
关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图