python中__init__后面加特殊符号_Python中的__init__到底是干什么的?

看到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())

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值