python一些定製方法(函數)

__str__() __call__() __repr__()方法

>>> class Student(object):
    def __init__(self, name):
        self.name = name

    def __call__(self):
        print('My name is %s.' % self.name)
    def __str__(self):
	return 'I am a print call for name:%s !'%self.name
    def __repr__(self):
	return 'I am a print var value for name:%s !'%self.name

>>> s = Student('lucy')
>>> s     //call __repr__()
I am a print var value for name:lucy !
>>> s()   // call __call__()
My name is lucy.
>>> print s    //call __str__()
I am a print call for name:lucy !

  



__str__是調用print 打印,
__repr__是直接寫變量時打印的

__iter__()方法


若是一個類想被用於for ... in循環,相似list或tuple那樣,就必須實現一個__iter__()方法
for ... in__iter__()

__getitem__()方法


要表現得像list那樣按照下標取出元素,須要實現方法

__getitem__()

__getattr__()方法


那就是寫一個方法,動態返回一個屬性

__getattr__()
class Student(object): def __init__(self): self.name = 'Michael' def __getattr__(self, attr): if attr=='score': return 99
  raise
AttributeError('\'Student\' object has no attribute \'%s\'' % attr) //調用不存在的屬性是,拋出
 
>>> s = Student() >>> s.name 'Michael' >>> s.score 99

本節介紹的是最經常使用的幾個定製方法,還有不少可定製的方法,請參考Python的官方文檔。http://docs.python.org/2/reference/datamodel.html#special-method-names
相關文章
相關標籤/搜索