Python面向对象高级编程
1.__slots__
通過Types包中的MethodType將外部方法與類對象進行綁定(該方法只能對綁定的對象生效)
"""a test module""" from types import MethodType__author__ = 'Jack Ma'class Student(object):"""a test class"""passdef 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"""passdef 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')passdef 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')passclass 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"""@propertydef score(self):return self._score@score.setterdef 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 = valuea = Student() a.score = 11 print a.score可以通過裝飾器的setter屬性 對score的設置屬性進行限制
3.多繼承
需要多繼承時,在第二個類及之后的類后加上MiXin實現
class MyTCPServer(TCPServer, CoroutineMixin):pass4.元類
用type()函數創建類
3個參數:
1.創建的類名 -- 字符串
2.父類 -- 元組
3.綁定的內容 -- 字典
def func(self, name):print "Hello %s !" % nameHello = type("Hello", (object,), {'hello': func}) a = Hello() a.hello("World") Hello World !除了使用type()動態創建類以外,要控制類的創建行為,還可以使用metaclass。
metaclass,直譯為元類,簡單的解釋就是:
當我們定義了類以后,就可以根據這個類創建出實例,所以:先定義類,然后創建實例。
但是如果我們想創建出類呢?那就必須根據metaclass創建出類,所以:先定義metaclass,然后創建類。
連接起來就是:先定義metaclass,就可以創建類,最后創建實例。
所以,metaclass允許你創建類或者修改類。換句話說,你可以把類看成是metaclass創建出來的“實例”。
?
轉載于:https://www.cnblogs.com/Msh0923/p/8087887.html
總結
以上是生活随笔為你收集整理的Python面向对象高级编程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 中国人工智能学会通讯——智能系统测评:挑
- 下一篇: 【12】Python函数学习(中)