@nemos
2017-05-05T14:54:40.000000Z
字数 6302
阅读 769
py
元类->类->实例
newtype = type(name, bases, dict) #返回一个新类型
直接定义在类内部的变量是绑定在类上面的
init中用self的是绑定在对象上面的
直接定义在类内部的为实例方法
类调用则为未绑定
类的成员加上双下划线即可外部无法直接访问
Secretive.__inaccessible <=>Secretive._Secretive__inaccessible
函数签名: super([type[, object-or-type]])
#旧式类class SongBird(Bird):def __init__(self):Bird.__init__(self)#新式类class SongBird(Bird):def __init__(self):super(SongBird, self).__init__()
官方文档的示例代码
class C(B):def method(self, arg):super().method(arg) # This does the same thing as:# super(C, self).method(arg)
obj.__bases__ #返回子类obj.__dict__ #包含实例属性的字典,以及类的所有可调用方法#可以代替普通的赋值操作#对象的__dict__为普通的字典,而类的为dictproxyobj.__class__ #获取对象类型即从哪里被实例化出来obj.__doc__ #显示文档信息obj.__module__ #显示当前操作的对象在哪个模块obj.__metaclass__ #指定类由谁实例化
property attr=property(fget=None, fset=None, fdel=None, doc=None)
class obj():def setValue():passdef getValue():pass#使用property函数value = property(getValue, setValue)
class Property(object):"Emulate PyProperty_Type() in Objects/descrobject.c"def __init__(self, fget=None, fset=None, fdel=None, doc=None):self.fget = fgetself.fset = fsetself.fdel = fdelif doc is None and fget is not None:doc = fget.__doc__self.__doc__ = docdef __get__(self, obj, objtype=None):if obj is None:return selfif self.fget is None:raise AttributeError("unreadable attribute")return self.fget(obj)def __set__(self, obj, value):if self.fset is None:raise AttributeError("can't set attribute")self.fset(obj, value)def __delete__(self, obj):if self.fdel is None:raise AttributeError("can't delete attribute")self.fdel(obj)def getter(self, fget):return type(self)(fget, self.fset, self.fdel, self.__doc__)def setter(self, fset):return type(self)(self.fget, fset, self.fdel, self.__doc__)def deleter(self, fdel):return type(self)(self.fget, self.fset, fdel, self.__doc__)
bool = callable(obj) #判断对象是否可以被调用#py3 中是hasattr()bool = getattr(obj, name[, default]) #确定属性值bool = hasattr(obj, name)None = setattr(obj, name, value)bool = isinstance(obj, class)issubclass(subclass, class)type = type(obj)
@staticmethod #静态方法@classmethod #类方法#类方法可以用类的具体具体对象直接调用#第一个参数传入调用的类
obj.__new__(self) #创建类实例并返回obj.__init__(self) #初始化实例obj.__del__(self) #构析函数
控制属性的访问的方法
obj.__getattribute__(self, name) #当name被访问时调用,不管存在与否obj.__getattr__(self, name) #当name被访问且不存在时,在被调用前先调用__getattribute__obj.__setattr__(self, name, value) #当name被赋值时调用obj.__delattr__(self, name) #删除时调用
def __setattr__(self, name, value): #错误用法self.name = value# 每当属性被赋值的时候(如self.name = value), ``__setattr__()`` 会被调用,这样就造成了递归调用。# 这意味这会调用 ``self.__setattr__('name', value)`` ,每次方法会调用自己。这样会造成程序崩溃。def __setattr__(self, name, value): #正确用法self.__dict__[name] = value # 给类中的属性名分配值
obj.__len__(self, key) #返回容器长度obj.__getitem__(self, key) #self[]产生的行为,可以用[]传入数据,或[::]传入切片对象,以及字符串等等# 以上两个方法实现不可变容器,加上以下实现可变容器obj.__setitem__(self, key, value) # self[key] = value 产生的行为obj.__delitem__(self, key) #删除元素 #del self[key]的实现obj.__iter__(self) #返回容器迭代器, for x in self时调用obj.__reversed__(self)obj.__contains__(self, item) # in时产生的行为,若没有定义会从迭代对象中一个一个找obj.__missing__(self, key) #找不到元素时触发的行为
obj.__instancecheck__(self, instance) #检查一个实例是不是你定义的类的实例obj.__subclasscheck__(self, subclass) #检查一个类是不是你定义的类的子类
obj.__call__(self, *args, *kwargs) #函数对象
class Entity:"调用实体来改变实体的位置"def __init__(self, size, x, y):self.x, self.y = x, yself.size = sizedef __call__(self, x, y):"改变实体的位置"self.x, self.y = x, y
with open('foo.txt') as bar:# do something with bar
obj.__enter__(self)obj.__exit__(self, exception_type, exception_value, traceback)
obj.__str__(self) #print时显示的内容obj.__add__(self, other) #加法操作
描述器是通过获取、设置以及删除的时候被访问的类。
# instance是拥有该描述器对象的一个实例。owner是拥有者本身value = descr.__get__(self, ins, owner) #当描述器的值被取得的时候的行为None = descr.__set__(self, ins, value) #定义了当描述器的值被改变的时候的行为None = descr.__delete(self, ins) #定义了当描述器的值被删除的时候的行为
实现了get的为非数据描述符
同时实现get,set的为数据描述符
class Meter(object):def __init__(self, value=0.0):self.value = float(value)def __get__(self, instance, owner):return self.valuedef __set__(self, instance, value):self.value = float(value)class Foot(object):def __get__(self, instance, owner):return instance.meter * 3.2808def __set__(self, instance, value):instance.meter = float(value) / 3.2808class Distance(object): #用米和英寸来表示两个描述器之间的距离meter = Meter(10)foot = Foot()########################>>>d = Distance()>>>print d.foot>>>print d.meter32.80810.0
obj.__copy__(self) #当ins.copy()被调用时产生的行为obj.__deepcopy__(self, memodict={}) #当ins.deepcopy()被调用时产生的行为
__cmp__(self, other) #是比较方法里面最基本的的魔法方法__eq__(self, other) #定义相等符号的行为,==__ne__(self,other) #定义不等符号的行为,!=__lt__(self,other) #定义小于符号的行为,<__gt__(self,other) #定义大于符号的行为,>__le__(self,other) #定义小于等于符号的行为,<=__ge__(self,other) #定义大于等于符号的行为,>=
__pos__(self) #实现一个取正数的操作__neg__(self) #实现一个取负数的操作__abs__(self) #实现一个内建的abs()函数的行为__invert__(self) #实现一个取反操作符(~操作符)的行为__round__(self, n) #实现一个内建的round()函数的行为__floor__(self) #实现math.floor()的函数行为__ceil__(self) #实现math.ceil()的函数行为__trunc__(self) #实现math.trunc()的函数行为
__add__(self, other) #实现一个加法__sub__(self, other) #实现一个减法__mul__(self, other) #实现一个乘法__floordiv__(self, other) #实现一个“//”操作符产生的整除操作()__div__(self, other) #实现一个“/”操作符代表的除法操作__truediv__(self, other) #实现真实除法__mod__(self, other) #实现一个“%”操作符代表的取模操作__divmod__(self, other) #实现一个内建函数divmod()__pow__ #实现一个指数操作(“**”操作符)的行为__lshift__(self, other) #实现一个位左移操作(<<)的功能__rshift__(self, other) #实现一个位右移操作(>>)的功能__and__(self, other) #实现一个按位进行与操作(&)的行为__or__(self, other) #实现一个按位进行或操作的行为__xor__(self, other) #__xor__(self, other)
__iadd__(self, other) #加法赋值__isub__(self, other) #减法赋值__imul__(self, other) #乘法赋值__ifloordiv__(self, other) #整除赋值,地板除,相当于 //= 运算符__idiv__(self, other) #除法赋值,相当于 /= 运算符__itruediv__(self, other) #真除赋值__imod_(self, other) #模赋值,相当于 %= 运算符__ipow__ #乘方赋值,相当于 **= 运算符__ilshift__(self, other) #左移赋值,相当于 <<= 运算符__irshift__(self, other) #左移赋值,相当于 >>= 运算符__iand__(self, other) #与赋值,相当于 &= 运算符__ior__(self, other) #或赋值__ixor__(self, other) #异或运算符,相当于 ^= 运算符
__int__(self) #转换成整型__long__(self) #转换成长整型__float__(self) #转换成浮点型__complex__(self) #转换成 复数型__oct__(self) #转换成八进制__hex__(self) #转换成十六进制__index__(self) #如果你定义了一个可能被用来做切片操作的数值型,你就应该定义__index____trunc__(self) #当 math.trunc(self) 使用时被调用__trunc__返回自身类型的整型截取__coerce__(self, other) #执行混合类型的运算