免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2770 | 回复: 0
打印 上一主题 下一主题

Python 中的类 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-12-04 21:38 |只看该作者 |倒序浏览
之前学Python,没关注其OOP,最近在用PyLucene,看其中Lucene In Action的实例代码,全是用类实现的。遂顺道补补Python OOP的课。不保证能系统的记录学习过程,所以分类为“Python 学习散记”。
用的书是,也是推荐的,>, >, >,应该都是经典书吧,作者就不说了。
----------------------------------------------------
1,Python中的类维护有一个名为 '__dict__'的字典,貌似所定义的类attribute 及 method 都在该字典中被记录和查找,所以当定义一个和之前定义的属性或方法同名的属性或方法是,之前的定义被覆盖,不可访问。如下例
#examples are written in Python2.5
Example 1
  1. class cls(object):
  2.     ambiguity = 'attribute of cls'
  3.     def ambiguity(self):
  4.         print 'method of cls'
复制代码
Example 2
  1. class cls2(object):
  2.     def ambiguity(self):
  3.         print 'method of cls2'
  4.     ambiguity = 'attribute of cls2'
复制代码
  1. ins = cls()    # ins is an instance of cls
  2. ins.ambiguity    # output: 'cls' object has no attribute 'ambituity'
  3. ins.ambituity()    # output: method of cls
  4. ins2 = cls2()    # ins2 is an instance of cls2
  5. ins2.ambiguity    # output:
  6. ins2.ambiguity()# output: method of cls2
复制代码
可见后申明的 ambiguity 完全覆盖的之前申明的 ambiguity。
------------------------------------------------------
2, Python中类及实例的属性值获取/查找的原则。
A: 类属性的获取,如cls.attr(其中cls是一个类名,如Example 1 中的cls
   a: 若 attr 存在于 cls.__dict__ 中,则返回其值。
   b: 否则,顺次查找cls的父类,若其__dict__中有键 attr 返回其值。若所有父类都没有,报错"type ---- has no attribute ----"
B: 类实例的属性值获取/查找的原则。如 ins.attr (其中 ins 是一个类实例)
   a: 查找本实例的__dict__(注意,实例也有自己的__dict__,区别于其所属的类的__dict__),有则返回其值。
   b: 否则,查找ins所属的类以及其父类的__dict__,有则返回值。无则抱错。
Example 3
  1. class One(object):
  2.     a = 'class attribute a in One'
  3. class Two(One):
  4.     b = 'class attribute b in Two'
  5.     c = 'class attribute c in Two'
  6.     d = 'class attribute d in Two'
  7.     def __init__(self):
  8.         self.b = 'instance att b in Two'
  9.         self.e = 'instance attr e i Two'
  10.         d = 'class attribute d of Two is changed.'
  11. ins = Two()
  12. ins.a    # output: class attribute a in One. (Principle B:b)
  13. ins.b    # output: instance attribute b in Two. (Principle B:a)
  14. ins.c    # output: class attribute c in Two. (Principle B:b)
  15. ins.e    # output: instance attr e in Two. (Principle B:a)
  16. ins.d    # output: class attribute d in Two. (Principle B:b)
复制代码
注意上述 ins.d 的结果并非'class attribute d of Two is changed'. 即 __init__()末行的赋值没有改变类属性Two.d的值,而只是“申明
”了一个__init__()函数的本地变量并赋值。若想在函数中使用类属属性必须家类名,如Two.d = 'class .....'


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/107345/showart_2111555.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP