您的位置:首页 > 编程语言 > Python开发

python 面向对象编程

2014-05-19 17:36 85 查看

实例
绑定与方法调用
子类,派生和继承
内建函数
私有性
􀁺 授权与包装
􀁺 新式类的高级特性
􀁺 相关模块

1 类

首先要知道的是python 2.2版本对类做出了更改。python2.2版本之后,如果你定义的类显示继承一个基类,那么这就是一个新式类。否则是旧式类。 python2.2中把类和类型做出了统一,所以对于新式类来说是下面这样的:

>>> class A:
...     __iv=1
...     v=2
...     def __ifoo(self):
...             print 'this method is invisible'
...     def foo(self):
...             print 'this method is visible'
...
>>>
>>> a=A()
>>> a.foo()
this method is visible
>>> a.__ifoo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: A instance has no attribute '__ifoo'
>>> a.v
2
>>> a.__iv
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: A instance has no attribute '__iv'


View Code
如图,上面类里的属性,只要前面加上双下划线,在类外面就访问不到了。当然在类的里面还是可以的。不过其实这是一种防君子不防小人的措施。因为在属性前面加了双下划线之后,python只是把属性的名字改成了_类名__属性名。 也就是前面添加了一个下划线还有一个类名。

>>> dir(A)
['_A__ifoo', '_A__iv', '__doc__', '__module__', 'foo', 'v']


所以你真的想访问还是可以访问的。

>>> a._A__ifoo()
this method is invisible
>>> a._A__iv
1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: