今天看到了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定义的变量也涉及到了,书上使用了一个较长的专门讨论这个的程序,我的当然也有用,能够提供一点参考。
晚上回来看A byte of Python,还没有看到这些复杂的东西,我写了个测试用的小程序,看看到底有的东西怎么回事,关于class定义的变量也涉及到了,书上使用了一个较长的专门讨论这个的程序,我的当然也有用,能够提供一点参考。
- # FileName: oo.py
- class FirstClass:
- def __init__ (self, x):
- self.x = x;
- def divide (self, y):
- return self.x//y
- class SecondClass(object):
- x = 10;
- __x = 18; #private
- __x__ = 20;
- def divide (self, y):
- return self.x//y #error: x//y; right: SecondClass.x//y and this
- print SecondClass.x
- firstClass = FirstClass(19)
- print firstClass.x
- print firstClass.divide(7)
- sc = SecondClass()
- print SecondClass.divide(sc,3)
- print sc.divide(3)
- print sc.x
- #print sc.__name__ #AttributeError: 'SecondClass' object has no attribute '__name__'
- print SecondClass.__name__
- print sc.__dict__ #{}
- print SecondClass.__dict__ #{'__module__':'__main__','divide':<function divide at 0x00BDCB70>, ....}
- print sc.divide #<bound method SecondClass.divide of <__main.SecondClass object at 0x00BD9BF0>>
- print SecondClass.divide #<unbound method SecondClass.divide>
- print sc._SecondClass__x #not sc._x that raises error
- print sc.__x__ #ok
- print SecondClass.__x__ #ok
- class ThirdClass(object):
- x = 10
- def __init__ (self, x):
- self.x = x
- def p (self):
- print "ThirdClass.x = ", ThirdClass.x
- print "self.x = ", self.x
- def __del__ (self):
- print "All are OVER!"
- tc = ThirdClass(15)
- tc.p() #10, 15. New instance does not change the original x