Python的面向对象之class二看
来源:互联网 发布:英克软件下载 编辑:程序博客网 时间:2024/05/18 02:56
关于old-style和new-style的一些差别,以及使用property内建函数。
- #coding: UTF-8
- #author: Hegc Huang
- #类的使用
- #结果看出,使用old-style的时候不会在调用add的时候调用那个__getattr__函数
- class oldclass:
- def __getattr__ (self, name):
- print "Old class, getattr : ", name
- return super(oldclass, self).__getattr__(name)
- def add (self):
- print "xx"
- class newclass(object):
- def __getattribute__ (self, name):
- print "new class, getattr : ", name
- return super(newclass, self).__getattribute__(name)
- def add (self):
- print "new class add"
- def __hash__ (self):
- return 'newclass'.__hash__()
- o = oldclass()
- o.add()
- n = newclass()
- n.add()
- print hash(n)
- #关于property的使用
- #我觉得一般来说直接使用一个变量来操作,而不要使用property更加方便直接
- #使用property的话还得使用辅助变量操作,挺麻烦的,一开始入prop那样是会出现
- #递归溢出的。下边的例子同时也让我明白了__v这种private变量的作用范围
- class prop(object):
- def __init__ (self, x, y):
- self.x = x
- self.y = y
- def __get (self):
- print 'Get method'
- return self.x*self.y
- def __set (self, r):
- print 'Set method'
- self.r = r
- r = property(__get, __set, doc='XXXXXX prop')
- p = prop(10, 9)
- print 'For get : ', p.r
- #p.r = 123 #recursion error, in fact, SET_method is not convenient to use
- print 'After set : ', p.r
- print prop.r.__doc__ #not p.r.__doc__
- class _prop(object):
- def __init__ (self, x, y):
- self.x = x
- self.y = y
- self.__r = None #for private use
- def __get (self):
- print 'Get method'
- if self.__r==None:
- self.__r = self.x*self.y
- return self.__r
- def __set (self, r):
- print 'Set method'
- self.__r = r
- r = property(__get, __set, doc='XXXXXX _prop')
- _p = _prop(34, 53)
- print '_prop , Get : ', _p.r #1802
- _p.r = 99
- print '_prop , Set : ', _p.r #92
- #print _p.__r #error
- Python的面向对象之class二看
- Python的面向对象之class初览
- Python学习之面向对象(class)
- 【Python】面向对象class
- 面向对象的python(二)
- python系列之 - 面向对象(二)
- python面向对象(二)之封装
- python 之面向对象
- python之面向对象
- Python之面向对象
- 面向对象的Perl 之二
- 面向对象的六大原则(之二)
- 面向对象的特征之二继承
- 看python官方说明学python-class-object-类、对象-之区域和名空间
- python入门(二十七):面向对象之封装
- python入门(二十八):面向对象之继承
- Python-面向对象 (二 继承)
- Python面向对象(二)
- 用java写的程序:1-100随机数相加
- Reader转化为Entity类时系统性能的测试报告(downmoon原创)
- NAT、防火墙的原理区别和分类
- HDU 2100 Lovekey
- Flash 文件格式解析
- Python的面向对象之class二看
- WebService的介绍
- HDU 1056 HangOver
- JSP 连接 Oracle
- 大数据量分页存储过程效率测试附代码
- 测你的反应能力-据说美国空军要求玩到2分钟
- PMP考试常见问题解答
- 背影
- PHP那些事:面向对象的方法重载