Python培训之__init__到底是干什么的?

发布时间:2022-11-28 09:37:47 人气:70 作者:多测师

  看到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的值根据每个对象指定,这表明了它作为对象的变量的本质。

Python培训之__init__到底是干什么的?

  例如我们定义一个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())

  以上内容为大家介绍了Python培训之__init__到底是干什么的?,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注多测师。https://www.e70w.com/xwzx/


返回列表
在线客服
联系方式

热线电话

17727591462

上班时间

周一到周五

二维码
线