__init__方法又成为构造方法,创造的方法会被自动的调用
以下为相应的__init__方法方法的展示与调用
以下是使用了__init__的方法
In [50]: class ball:
...: def __init__(self,name):
...: self.name=name
...: def kick(self):
...: print "我叫 %s,该死的是谁踢了我。。。。" % self.name
...:
In [52]: b=ball('土豆')
In [53]: b.kick()
我叫 土豆,该死的是谁踢了我。。。。
以下是未使用init的方法
In [37]: class ball:
...: def setName(self,name):
...: self.name=name
...: def kick(self):
...: print "my name is %s,shit who shot me...." % self.name
...:
In [38]: a=ball()
In [39]: a.setName('球A')
In [40]: b=ball()
In [41]: b.setName('westing')
In [43]: c=ball()
In [44]: c.setName('球B')
In [45]: a.kick()
my name is 球A,shit who shot me....
In [46]: b.kick()
my name is westing,shit who shot me....
In [47]: c.kick()
my name is 球B,shit who shot me....
对比之后就会发现使用了init的方法的类更加的简洁
函数的私有化
若想将一个变量进行私有化,只需在相应的变量名字前加上 ’_‘即可:
In [54]: class person:
...: name='andrew'
...:
In [55]: a=person()
In [56]: a.name
Out[56]: 'andrew'
In [57]: class person:
...: __name='andrew'
...:
In [58]: a=person()
In [59]: a.__name
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-59-5d5520ef9fe0> in <module>()
----> 1 a.__name
AttributeError: person instance has no attribute '__name'
In [60]: a.name
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-60-c0a6f6c60584> in <module>()
----> 1 a.name
AttributeError: person instance has no attribute 'name'
一旦变量名字的前方加上’_’ 函数就会对相应的变量进行私有化,这时要想进行相应的引用只有在函数内部引用,在外部变量名字会被隐藏起来。
调用的方法如下:
In [61]: class person:
...: __name='andrew'
...: def getName(self):
...: return self.__name
...:
In [63]: p=person()
In [64]: p.name
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-64-1c57ed665d7c> in <module>()
----> 1 p.name
AttributeError: person instance has no attribute 'name'
In [65]: p.__name
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-65-5fe22c1da0df> in <module>()
----> 1 p.__name
AttributeError: person instance has no attribute '__name'
In [66]: p.getName()
Out[66]: 'andrew'
其实加上’_‘也就相当于进行类名的重整,也就是你加上的只是’__‘但是python 会默认给你加上的为_类名__变量名 的形式,
以下就是直接访问重整变量__变量 类型变量
“`
In [67]: class person:
…: __name=’andrew’
…:
In [68]:
In [68]: p._person__name
Out[68]: ‘andrew’
本文介绍Python中__init__方法的使用,通过实例对比展示其如何简化类的实例化过程。此外,还详细解释了如何通过在属性名称前添加下划线实现属性的私有化,并提供了访问私有属性的正确方式。
221

被折叠的 条评论
为什么被折叠?



