chapter9: python 类的方法,属性,迭代器(new[old]-type class,[un]bound method,super,protocol,property,iterators)

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 

Question: p207 create an infinite sequence 
Protocol:这里的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. 

If given, doc will be the docstring of the property attribute. Otherwise, the property will copy fget's docstring (if it exists). This makes it possible to create read-only properties easily using property() as a decorator:

大概含义是,如果要使用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?  


未完待续

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值