chapter 9:Magic Methods, Properties, and Iterators
1 new-type class & old-type class
从python 2.2 起,如果一个类继承自object 对象(或者它是任何内建类型如list, dict, file 的子类),那它就是一个new-style class 。在此之前,Python不允许通过继承内建类型生成新类,也根本没有object 这个对象 。
# old-type 举例
#! /usr/bin/python
__metaclass__ = type
class Person:
defshow():
print ‘just a test!’
p = Person()
p.__init__() # init() 是object对象的method,新类才有;如果以class Person的方式,则为old-type,则需要在最初标示__metaclass__= type,标示为new-type
# new-type 举例
#! /usr/bin/python
Class Person(object): # 内容略,和上列有同样效果
2 magic method-> constructors 构造函数
class TestConstructor(object):
#self.param2 = 2 wrong
param1 = 1
def __init__(self,value=41):
self.somevalue = value
def f1(self): #must have self
pass
t1 = TestConstructor()
print t1.somevalue
t2 = TestConstructor('value can be assigned too')
print t2.somevalue
t2.f1()
print t2.param1
print TestConstructor.param1
3 bound method /unbound method & super function
简单说:绑定的只通过实例(instance)调用,unbound只通过类(class)调用
super function 和unbound method 区别?
Super 更直观,灵活;如有多个父类时可以一次性获取,返回superclass object
class Bird(object):
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print 'eat!!'
self.hungry = False
else :
print 'i am full'
class SongBird(Bird): # must be superClass,can use unbound method in class
##override
def __init__(self):
#Bird.__init__(self) # using unbound method
super(SongBird,self).__init__() # same with upper,using super
self.song = 'music time'
def sing(self):
print self.song
sb1 = SongBird()
sb1.eat()
sb1.sing()
4 The Basic Sequence and Mapping Protocol
seq = [1,2,3,3]
dic = {'name':'lili','no':10}
print seq.__len__()
print seq.__getitem__(2)
seq.__setitem__(2,20)
print seq.__getitem__(2)
seq.__delitem__(1) #delete seq[1] #[1,20,3]
print seq
5 property function
property( [fget[, fset[, fdel[, doc]]]])Return a property attribute for new-style classes (classes that derive from object).
fget is a function for getting an attribute value, likewise fset is a function for setting, and fdel a function for del'ing, an attribute.
大概含义是,如果要使用property函数,首先定义class的时候必须是object的子类。通过property的定义,当获取成员x的值时,就会调用getx函数,当给成员x赋值时,就会调用setx函数,当删除x时,就会调用delx函数。使用属性的好处就是因为在调用函数,可以做一些检查。如果没有严格的要求,直接使用实例属性可能更方便。
class C(object):
def __init__(self):
self._x = None
self._y = None
def getx(self):
print '------getx'
return self._x,100,200
def setx(self, value):
print '------setx'
self._x,self._y = value
def delx(self):
print '------delx'
del self._x
xx = property(getx, setx, delx, "I'm the 'x' property.")
c1 = C()
c1._x = 10
# 使用property,实现调用函数getx,只读获取return值
print c1.xx # ------getx (10, 100 ,200)
# 使用property,实现调用函数setx,赋值
c1.xx = 11,22
print c1._x,c1._y # ------setx 11 22
print '--', C.xx.__doc__ # I'm the 'x' property
# 如何调用delx?
未完待续