面向对象编程:公有和私有

公有和私有:苍井空是世界的,老婆是自己的。

理论上python 的属性和方法都是公有的,都可以通过 .操作符进行调用,但是可以在类内部通过 双下划线 将其指定为私有

实例1

>>> class Pereson:
    name = '曹操'

>>> p = Person()
>>> p.name #这里可以将类Person实例化为p,因为name是公有的
'曹操'

 

实例2

>>> class Person:

...     __name = '曹操'

... 

>>> p = Person()

>>> p.__name  #在类Person中已经将name私有化,因此在这里就无法调用,如果要返回name,只能在类的内部返回。见实例3

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

AttributeError: Person instance has no attribute '__name'

 

实例3

>>> class Person:

...     __name = '曹操'

...     def getName(self):#在类的内部定义一个函数获取私有化的__name

...             return self.__name

... 

>>> p = Person()

>>> p.getName()

'曹操'

 

posted @ 2017-01-30 11:44  道高一尺  阅读(166)  评论(0)    收藏  举报