知识点
1、类当字典Key使用
class User(object): pass class Role(object): pass class Bar(object): def __init__(self,b): self.b=b _registry={ User:Bar(User), Role:Bar(Role) } for k,v in _registry.items(): print(k,v.b)
这里的k是等于v.b的
2、根据models类查找该类所在app名称和在数据库中的表名
- 获取models所在app名称
from app01 import models as m1 from app02 import models as m2 def index(request): print(m1.UserInfo) print(m2.Permission) #获取当前models类所在app名称,以及小写类名 print(m1.UserInfo._meta.app_label) print(m2.Permission._meta.app_label) return HttpResponse('.......')
- 获取当前models类在数据库中的表名
from app01 import models as m1 from app02 import models as m2 def index(request): print(m1.UserInfo) print(m2.Permission) #获取当前models类在数据库中的表名 print(m1.UserInfo._meta.model_name) print(m2.Permission._meta.model_name) return HttpResponse('.......')
最终版:
from app01 import models as m1 from app02 import models as m2 def index(request): _registry={ m1.UserInfo:'1', m2.Permission:'2' } for k,v in _registry.items(): print(k._meta.app_label,k._meta.model_name) return HttpResponse('.......')
3、方法和函数的区别
根据调用它的方式来确定是函数还是方法。
实例化类后,调用的函数为绑定方法
class A(object): def a(self): pass def b(): pass print(A.a)#function print(b)#function aa=A() print(aa.a)#bound method
检测函数或方法
from types import MethodType,FunctionType def check(arg): if isinstance(arg,MethodType): print("方法") elif isinstance(arg,FunctionType): print("函数") else: print("不认识")
类的静态字段和多个实例对象公用
4、yield
迭代器,需要一个返回一个,节约内存
def get_result(data_list): for row in data_list: tmp="%s%s" % (row.name,row.pwd) yield tmp
5、反射
getattr()
def test(request): from app01 import models #自定义需要显示的字段 list_display=['id','title'] #存储字段别名 header_list=[] for name in list_display: # 获取需要显示的字段的别名,即verbose_name header_list.append(models.UserInfo._meta.get_field(name).verbose_name) user_queryset=models.UserInfo.objects.all() for item in user_queryset: row=[] for field in list_display: #通过getattr()方法获取item对象的指定属性,即需要的数据 row.append(getattr(item,field)) print(row)
6、装饰器
functools.wraps()装饰器保留原函数的信息
import functools def wrapper(func): @functools.wraps(func)#保留原函数的原信息,如函数名,函数备注之类数据,否则被装饰过的函数名会变成inner def inner(*args,**kwargs): return func(*args,**kwargs) return inner def f1(): print('f1') @wrapper def f2(): print('f1') print(f1.__name__) print(f2.__name__)