Python的面向对象之class二看

来源:互联网 发布:英克软件下载 编辑:程序博客网 时间:2024/05/18 02:56
关于old-style和new-style的一些差别,以及使用property内建函数。
  1. #coding: UTF-8
  2. #author: Hegc Huang
  3. #类的使用
  4. #结果看出,使用old-style的时候不会在调用add的时候调用那个__getattr__函数
  5. class oldclass:
  6.     def __getattr__ (self, name):
  7.         print "Old class, getattr : ", name
  8.         return super(oldclass, self).__getattr__(name)
  9.     def add (self):
  10.         print "xx"
  11. class newclass(object):
  12.     def __getattribute__ (self, name):
  13.         print "new class, getattr : ", name
  14.         return super(newclass, self).__getattribute__(name)
  15.     def add (self):
  16.         print "new class add"
  17.     def __hash__ (self):
  18.         return 'newclass'.__hash__()
  19. o = oldclass()
  20. o.add()
  21. n = newclass()
  22. n.add()
  23. print hash(n)
  24. #关于property的使用
  25. #我觉得一般来说直接使用一个变量来操作,而不要使用property更加方便直接
  26. #使用property的话还得使用辅助变量操作,挺麻烦的,一开始入prop那样是会出现
  27. #递归溢出的。下边的例子同时也让我明白了__v这种private变量的作用范围
  28. class prop(object):
  29.     def __init__ (self, x, y):
  30.         self.x = x
  31.         self.y = y
  32.     def __get (self):
  33.         print 'Get method'
  34.         return self.x*self.y
  35.     def __set (self, r):
  36.         print 'Set method'
  37.         self.r = r
  38.         
  39.     r = property(__get, __set, doc='XXXXXX prop')
  40. p = prop(109)
  41. print 'For get : ', p.r
  42. #p.r = 123   #recursion error, in fact, SET_method is not convenient to use
  43. print 'After set : ', p.r
  44. print prop.r.__doc__    #not p.r.__doc__
  45. class _prop(object):
  46.     def __init__ (self, x, y):
  47.         self.x = x
  48.         self.y = y
  49.         self.__r = None #for private use
  50.     def __get (self):
  51.         print 'Get method'
  52.         if self.__r==None:
  53.             self.__r = self.x*self.y
  54.         
  55.         return self.__r
  56.     def __set (self, r):
  57.         print 'Set method'
  58.         self.__r = r
  59.         
  60.     r = property(__get, __set, doc='XXXXXX _prop')
  61. _p = _prop(3453)
  62. print '_prop , Get : ', _p.r    #1802
  63. _p.r = 99
  64. print '_prop , Set : ', _p.r    #92
  65. #print _p.__r   #error

原创粉丝点击