python中的内置函数(双下划线)

1.python 中__name__ = '__main__' 的作用

如果我们是直接执行某个.py文件的时候,该文件中那么”__name__ == '__main__'“是True,但是我们如果从另外一个.py文件通过import导入该文件的时候,这时__name__的值就是我们这个py文件的名字而不是__main__。

这个功能还有一个用处:调试代码的时候,在”if __name__ == '__main__'“中加入一些我们的调试代码,我们可以让外部模块调用的时候不执行我们的调试代码,但是如果我们想排查问题的时候,直接执行该模块文件,调试代码能够正常运行!

2.其他常用

x.__contains__(y) 等价于 y in x, 在list,str, dict,set等容器中有这个函数
__base__, __bases__, __mro__, 关于类继承和函数查找路径的。
class.__subclasses__(), 返回子类列表
x.__call__(...) == x(...)
x.__cmp__(y) == cmp(x,y)
x.__getattribute__('name') == x.name == getattr(x, 'name'),  比__getattr__更早调用
x.__hash__() == hash(x)
x.__sizeof__(), x在内存中的字节数, x为class得话, 就应该是x.__basicsize__
x.__delattr__('name') == del x.name
__dictoffset__ attribute tells you the offset to where you find the pointer to the __dict__ object in any instance object that has one. It is in bytes.
__flags__, 返回一串数字,用来判断该类型能否被序列化(if it's a heap type), __flags__ & 512
S.__format__, 有些类有用
x.__getitem__(y) == x[y], 相应还有__setitem__, 某些不可修改类型如set,str没有__setitem__
x.__getslice__(i, j) == x[i:j], 有个疑问,x='123456789', x[::2],是咋实现得
__subclasscheck__(), check if a class is subclass
__instancecheck__(), check if an object is an instance
__itemsize__, These fields allow calculating the size in bytes of instances of the type. 0是可变长度, 非0则是固定长度
x.__mod__(y) == x%y, x.__rmod__(y) == y%x
x.__module__ , x所属模块
x.__mul__(y) == x*y,  x.__rmul__(y) == y*x

__reduce__, __reduce_ex__ , for pickle

__slots__ 使用之后类变成静态一样,没有了__dict__, 实例也不可新添加属性

__getattr__ 在一般的查找属性查找不到之后会调用此函数

__setattr__ 取代一般的赋值操作,如果有此函数会调用此函数, 如想调用正常赋值途径用 object.__setattr__(self, name, value)

__delattr__ 同__setattr__, 在del obj.name有意义时会调用

 

参考文档:

1.python:浅析python 中__name__ = '__main__' 的作用:https://www.cnblogs.com/alan-babyblog/p/5147770.html

2.python中那些双下划线开头得函数和变量--转载:https://www.cnblogs.com/nkwy2012/p/6264031.html

 

转载于:https://my.oschina.net/u/3018050/blog/1794071

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值