python學習筆記(七),python學習筆記

來源:互聯網
上載者:User

python學習筆記(七),python學習筆記

一. 為類動態添加屬性和方法:

1. 動態給一個執行個體添加屬性和方法:

給一個執行個體綁定的方法,對另一個執行個體是不起作用的。

class Student(object):    passs = Student()s.name = 'Michael' # 動態給執行個體綁定一個屬性print s.namedef set_age(self, age): # 定義一個函數作為執行個體方法    self.age = age    from types import MethodTypes.set_age = MethodType(set_age, s, Student) # 給執行個體綁定一個方法s.set_age(25) # 調用執行個體方法print s.age # 測試結果
2. 動態給一個類添加屬性和方法:
class Student(object):    passs = Student()from types import MethodTypedef set_score(self, score):    self.score = score    Student.set_score = MethodType(set_score, None, Student)s.set_score(100)print s.score

二. 使用__slots__

使用__slots__可以限制class能添加的屬性:

class Student(object):    __slots__ = ('name', 'age') # 用tuple定義允許綁定的屬性名稱s = Student() # 建立新的執行個體s.name = 'Michael' # 綁定屬性'name's.age = 25 # 綁定屬性'age'
注意:__slots__定義的屬性僅對當前類起作用,對繼承的子類是不起作用的。

三. 使用@property

@property負責把一個方法變成屬性調用的:

class Student(object):    @property    def score(self):        return self._score    @score.setter    def score(self, value):        if not isinstance(value, int):            raise ValueError('score must be an integer!')        if value < 0 or value > 100:            raise ValueError('score must between 0 ~ 100!')        self._score = value        s = Student()s.score = 60 # OK,實際轉化為s.set_score(60)print s.score # OK,實際轉化為s.get_score()

四. 多重繼承:

python允許使用多重繼承,例如:Dog繼承了Animal和Runnable

class Animal(object):    passclass Runnable(object):    def run(self):        print('Running...')        class Dog(Animal, Runnable):    pass
五. 定製類:

1. __str__

相當於java中的toString

class Student(object):    def __init__(self, name):        self.name = name        def __str__(self):        return 'Student object (name: %s)' % self.nameprint Student('Michael') # Student object (name: Michael)
2.__iter__

如果一個類想變成list或tuple可以被迴圈(for .. in),那麼必須實現__iter__方法,該方法返回一個迭代對象,並不斷調用該迭代對象的next()方法拿到迴圈的下一個值:

class Fib(object):    def __init__(self):        self.a, self.b = 0, 1 # 初始化兩個計數器a,b    def __iter__(self):        return self # 執行個體本身就是迭代對象,故返回自己    def next(self):        self.a, self.b = self.b, self.a + self.b # 計算下一個值        if self.a > 100000: # 退出迴圈的條件            raise StopIteration();        return self.a # 返回下一個值    for n in Fib():    print n
3.__getitem__

通過下標擷取元素,需要實現__getitem__

class Fib(object):    def __init__(self):        self.a, self.b = 0, 1 # 初始化兩個計數器a,b    class Fib(object):    def __getitem__(self, n):        a, b = 1, 1        for x in range(n):            a, b = b, a + b        return af = Fib()print f[0]
4.__getattr__

想要動態返回一個屬性,需要實現__getattr__

如:調用不存在的屬性score時,python會試圖調用__getattr__(self, 'score')來嘗試獲得屬性

class Student(object):    def __init__(self):        self.name = 'Michael'    def __getattr__(self, attr):        if attr=='score':            return 99s = Student()print s.name  # 'Michael'print s.score  # 99
5.__call__

調用類本身:

class Student(object):    def __init__(self, name):        self.name = name    def __call__(self):        print('My name is %s.' % self.name)        s = Student('Michael')print s()  # My name is Michael.

六. 使用元類:

1. type()

type() 函數可以查看一個類的類型或一個變數的類型

type() 函數也可以建立出新的類型:比如建立一個Hello類

def fn(self, name='world'): # 先定義函數    print('Hello, %s.' % name)Hello = type('Hello', (object,), dict(hello=fn)) # 建立Hello classh = Hello()print h.hello()  # Hello, world.print(type(Hello))  # <type 'type'>print(type(h))  # <class '__main__.Hello'>
要建立一個class對象,type()函數依次傳入3個參數:

1) class的名稱

2) 繼承的父類集合,注意python支援多重繼承,如果只有一個父類,別忘了tuple的單元素寫法

3) class的方法名稱與函數綁定,這裡我們把函數fn綁定到方法名hello上


2. metaclass

元類 - 估計這個東東和java的class類似,不深究。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.