关于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