Python的面向对象之class初览

今天看到了python的面向对象的class部分,下午看Python in a nutshell,作者见了很多东西,但是都没有讲得很清楚,说些new-style的class内容,包括一些discriptor如__get__、__set__的,都不知道怎么回事,还有new-style中的__new__ 也不明白。我觉得现在2.5.4使用的__init__方法就已经很好了,为什么改动那么大呢,虽然好象写不写__new__没什么关系,因为它由系统来调用,实例话时仍然使用xx = XX()就行。
晚上回来看A byte of Python,还没有看到这些复杂的东西,我写了个测试用的小程序,看看到底有的东西怎么回事,关于class定义的变量也涉及到了,书上使用了一个较长的专门讨论这个的程序,我的当然也有用,能够提供一点参考。
  1. # FileName: oo.py
  2. class FirstClass:
  3.     def __init__ (self, x):
  4.         self.x = x;
  5.     def divide (self, y):
  6.         return self.x//y
  7. class SecondClass(object):
  8.     x = 10;
  9.     __x = 18;   #private
  10.     __x__ = 20;
  11.     def divide (self, y):
  12.         return self.x//y    #error: x//y;  right: SecondClass.x//y and this
  13. print SecondClass.x
  14. firstClass = FirstClass(19)
  15. print firstClass.x
  16. print firstClass.divide(7)
  17. sc = SecondClass()
  18. print SecondClass.divide(sc,3)
  19. print sc.divide(3)
  20. print sc.x
  21. #print sc.__name__  #AttributeError: 'SecondClass' object has no attribute '__name__'
  22. print SecondClass.__name__
  23. print sc.__dict__   #{}
  24. print SecondClass.__dict__  #{'__module__':'__main__','divide':<function divide at 0x00BDCB70>, ....}
  25. print sc.divide    #<bound method SecondClass.divide of <__main.SecondClass object at 0x00BD9BF0>>
  26. print SecondClass.divide    #<unbound method SecondClass.divide>
  27. print sc._SecondClass__x    #not sc._x that raises error
  28. print sc.__x__    #ok
  29. print SecondClass.__x__ #ok
  30. class ThirdClass(object):
  31.     x = 10
  32.     def __init__ (self, x):
  33.         self.x = x
  34.     def p (self):
  35.         print "ThirdClass.x = ", ThirdClass.x
  36.         print "self.x = "self.x
  37.     def __del__ (self):
  38.         print "All are OVER!"
  39. tc = ThirdClass(15)
  40. tc.p()  #10, 15. New instance does not change the original x

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值