__slots__ 例子,设置__slots__ 以外的属性的时候就会报错
class Student(cobject): __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称 >>> s = Student() # 创建新的实例 >>> s.name = 'Michael' # 绑定属性'name' >>> s.age = 25 # 绑定属性'age' >>> s.score = 99 # 绑定属性'score' Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Student' object has no attribute 'score' @property,使用装饰器的写法, @property 广泛应用在类的定义中,可以让调用者写出简短的代码,同时保证对参数进行必要的检查,这样,程序运行时就减少了出错的可能性。class Screen(object): @property def width(self): return self._width @property def height(self): return self._height @width.setter def width(self,value): self._width = value @height.setter def height(self,value): self._height = value @property def resolution(self): return 888-self._height
s = Screen() s.width = 20 print(s.width) s.height = 30 print(s.height) print(s.resolution)
多重继承,可继承多个父类.这样就不会有很多层级关系。都是点对点的关系1
class MyUDPServer(UDPServer, ThreadingMixIn):
枚举类,个人目前觉得枚举类可以用来存储一些唯一值,因为有@unique,如果有重复就会报错
from enum import Enum,unique
例1
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')) 例2 @unique class Weekday(Enum): Sun = 0 Mon = 1 Tue = 2 Wed = 3 print(Month.Jan.value) for k,v in Weekday.__members__.items(): print(k,'=>',v) print(k,'=>',v.value)
元类
要创建一个class对象,type()函数依次传入3个参数:
class的名称;继承的父类集合,注意Python支持多重继承,如果只有一个父类,别忘了tuple的单元素写法;class的方法名称与函数绑定,这里我们把函数fn绑定到方法名hello上。通过type()函数创建的类和直接写class是完全一样的,因为Python解释器遇到class定义时,仅仅是扫描一下class定义的语法,然后调用type()函数创建出class。
正常情况下,我们都用class Xxx...来定义类,但是,type()函数也允许我们动态创建出类来,也就是说,动态语言本身支持运行期动态创建类,这和静态语言有非常大的不同,要在静态语言运行期创建类,必须构造源代码字符串再调用编译器,或者借助一些工具生成字节码实现,本质上都是动态编译,会非常复杂。
例子
声明fn函数
def fn(self,name="wold"): print('hello, %s.'%name)
调用type函数创建类,参1 类名 参2 (object,) 参3 dict(类方法名=函数名) Hello = type('Hello',(object,),dict(hello=fn)) h = Hello() h.hello()