常用内建属性
# 函数
__new__ #创建实例所需的方法
__init__ #构造初始化函数,在__new__内部调用
__repr__ #值打印时调用,打印返回值
__call__ #实例当函数调用时执行
__iter__ #返回迭代器,实例被迭代执行时先调用此函数
__getitem__ #下标读取不在属性时调用
__setitem__ #下标设置属性时调用,self.__dict__[k]=v
__delitem__ #下标删除实例属性时调用
__getattr__ #.操作读取时调用
__getattribute__ #.操作读取时调用,定以后个体attr不生效
__setattr__ #.操作设置属性时调用
__delattr__ #.操作删除实例属性时调用
# 格式转换
__int__ #被int包裹时调用,返回转换结果
__str__ #被str包裹时调用,返回转换结果
# 运算符重载
__add__ #加法,返回运算结果,__add__(self,other)
# 实例属性
__class__ #返回实例所在的类
__dict__ #实例的自定义属性
__doc__ #类文档,help(类或者实例)
# 类属性
__bases__ #当前类的所有父类
类相关内置函数
isinstance(object,classinfo) #判断实例是否属于类
issubclass(class,classinfo) #判断继承关系
hasattr(object,name) #判断存在
getattr(object,name) #获取
setattr(object,name,value) #修改或设置属性
delattr(object,name) #删除实例属性
dir([object]) #返回参数的属性、方法列表,无参数获取当前模块
super(type[, object-or-type]) #获取type的父类
类属性和实例实行
__dict__
:只返回实例属性
dir([object])
:返回所有属性
__new__
- 真正的构造函数
class C:
def __new__(cls, *args, **kwargs):
print('new')
new=super(cls,cls).__new__(cls, *args, **kwargs)
# 返回new时会自动调用init,否则不会调用init,可以手动调用
# cls.__init__(new, *args, **kwargs)
return new
def __init__(self, *args, **kwargs):
print('init')
super
- 与c++不同,python允许不构造父类
class parent:
def __init__(self):
print('parent')
def func(self):
print('pfunc')
class son(parent):
def __init__(self):
super(son,self).__init__()
print('son')
def func(self):
print('sfunc')
s=son()
s.func()
super(son,s).func()
类方法@classmethod
class C:
def __init__(self, *args, **kwargs):
print(init)
# cls时类本身
@classmethod
def out_init(cls, *args, **kwargs):
return cls(*args, **kwargs)
静态方法@staticmethod
class C:
@staticmethod
def sta_func():
print('sta_func')
元类
- type(name, bases, dict)
- 设置的均为类属性
func=lambda x:print('i am func')
C = type('C',(object,),{'num':0,'func':func})
c=C()
c.func()
print([x for x in dir(c) if not x.endswith('__')])
设计模式
单例
- 实例用同一个内存
class Foo: # 单例模式
__v=None
@classmethod
def ge_instance(cls):
if cls.__v:
return cls.__v
else:
cls.__v=Foo()
return cls.__v
obj1=Foo.ge_instance()
print(obj1)
obj2=Foo.ge_instance()
print(obj2)
obj3=Foo.ge_instance()
print(obj3)