1. 程式人生 > >Python面向對象高級編程

Python面向對象高級編程

project 面向對象高級編程 tee 高級 student 我們 error 建行 imp

1.__slots__

通過Types包中的MethodType將外部方法與類對象進行綁定(該方法只能對綁定的對象生效)

"""a test module"""
from types import MethodType


__author__ = Jack Ma


class Student(object):
    """a test class"""
    pass


def set_name(self, name):
    self.name = name;


a = Student()
a.set_name = MethodType(set_name, a, Student)
a.set_name(
"Jack") print a.name

通過Types包中的MethodType將外部方法與類進行綁定(該方法能夠被該類的所有對象使用)

"""a test module"""
from types import MethodType


__author__ = Jack Ma


class Student(object):
    """a test class"""
    pass


def set_name(self, name):
    self.name = name;


a = Student()
b = Student()
Student.set_name 
= MethodType(set_name, None, Student) a.set_name("Jack") b.set_name("Tom") print a.name print b.name

而當我們想對一個類可以賦予的屬性進行限制,用到類的__slots__參數即可,__slots__賦值使用字符串為成員的元組進行賦值

class Student(object):
    """a test class"""
    __slots__ = (name, age)
    pass


def set_name(self, name):
    self.name = name;


a 
= Student() Student.set_name = MethodType(set_name, None, Student) a.set_name("Jack") a.sex = "Male" print a.name, a.sex

結果是sex屬性插入不了,報錯

Traceback (most recent call last):
  File "F:/PyProject/test2.py", line 23, in <module>
    a.sex = "Male"
AttributeError: Student object has no attribute sex

但是方法可以插入到類中

註意:使用__slots__要註意,__slots__定義的屬性僅對當前類起作用,對繼承的子類是不起作用的。除非在子類中也定義__slots__,這樣,子類允許定義的屬性就是自身的__slots__加上父類的__slots__

from types import MethodType


__author__ = Jack Ma


class Student(object):
    """a test class"""
    __slots__ = (name, age)
    pass


class Class1(Student):
    """a test son Class"""
    __slots__ = ()


def set_name(self, name):
    self.name = name;


a = Class1()
Class1.set_name = MethodType(set_name, None, Class1)
a.set_name("Jack")
a.sex = "Male"
print a.name, a.sex

此時,父類的__slots__限制才能生效

2.使用@property

class Student(object):
    """a test class"""
    @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


a = Student()
a.score = 11
print a.score

可以通過裝飾器的setter屬性 對score的設置屬性進行限制

3.多繼承

需要多繼承時,在第二個類及之後的類後加上MiXin實現

class MyTCPServer(TCPServer, CoroutineMixin):
    pass

4.元類

用type()函數創建類

3個參數:

1.創建的類名 -- 字符串

2.父類 -- 元組

3.綁定的內容 -- 字典

def func(self, name):
    print "Hello %s !" % name


Hello = type("Hello", (object,), {hello: func})
a = Hello()
a.hello("World")
Hello World !

除了使用type()動態創建類以外,要控制類的創建行為,還可以使用metaclass。

metaclass,直譯為元類,簡單的解釋就是:

當我們定義了類以後,就可以根據這個類創建出實例,所以:先定義類,然後創建實例。

但是如果我們想創建出類呢?那就必須根據metaclass創建出類,所以:先定義metaclass,然後創建類。

連接起來就是:先定義metaclass,就可以創建類,最後創建實例。

所以,metaclass允許你創建類或者修改類。換句話說,你可以把類看成是metaclass創建出來的“實例”。

Python面向對象高級編程