@nemos
2017-05-05T14:54:40.000000Z
字数 6302
阅读 738
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__为普通的字典,而类的为dictproxy
obj.__class__ #获取对象类型即从哪里被实例化出来
obj.__doc__ #显示文档信息
obj.__module__ #显示当前操作的对象在哪个模块
obj.__metaclass__ #指定类由谁实例化
property attr=property(fget=None, fset=None, fdel=None, doc=None)
class obj():
def setValue():
pass
def 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 = fget
self.fset = fset
self.fdel = fdel
if doc is None and fget is not None:
doc = fget.__doc__
self.__doc__ = doc
def __get__(self, obj, objtype=None):
if obj is None:
return self
if 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, y
self.size = size
def __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.value
def __set__(self, instance, value):
self.value = float(value)
class Foot(object):
def __get__(self, instance, owner):
return instance.meter * 3.2808
def __set__(self, instance, value):
instance.meter = float(value) / 3.2808
class Distance(object): #用米和英寸来表示两个描述器之间的距离
meter = Meter(10)
foot = Foot()
########################
>>>d = Distance()
>>>print d.foot
>>>print d.meter
32.808
10.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) #执行混合类型的运算