Python2筆記(十)—— 特殊方法

特殊方法

特殊方法定義在class中;調用時只需實現調用的和關聯的方法;

__str__()和__repr__()

將類作爲屬性直接訪問

# -*- coding: utf-8 -*-


class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return '(Person: %s, %s)' % (self.name, self.age)


p1 = Person('p1', 20)
print p1

結果:

(Person: p1, 20)

Python 定義了**__str__()__repr__()兩種方法,__str__()用於顯示給用戶,而__repr__()**用於顯示給開發人員。

__cmp__

intstr 等內置數據類型排序時,Python的 sorted() 按照默認的比較函數 cmp 排序,但是,如果對一組 Student 類的實例排序時,就必須提供我們自己的特殊方法 cmp():

# -*- coding: utf-8 -*-


class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return '(Person: %s, %s)' % (self.name, self.age)

    __repr__ = __str__

    def __cmp__(self, s):
        if self.name < s.name:
            return -1
        elif self.name > s.name:
            return 1
        else:
            return 0


L = [Person('pa1', 20), Person('pb2', 20), Person('pb1', 20)]
print sorted(L)

結果:

[(Person: pa1, 20), (Person: pb1, 20), (Person: pb2, 20)]

__len__()

返回元素的個數。

類型轉換

 print int(12.34)
 print float(12)

結果:

12

12.0

@property

第一個score(self)是get方法,用@property裝飾,第二個score(self, score)是set方法,用@score.setter裝飾,@score.setter是前一個@property裝飾後的副產品。

__slots__

__slots__的目的是限制當前類所能擁有的屬性,如果不需要添加任意動態的屬性,使用__slots__也能節省內存。

__call__()

一個類實例也可以變成一個可調用對象,只需要實現一個特殊方法**__call__()**。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章