做图表的网站推荐,网站建设自己能做吗,大连企业建设网站,丽江市企业网站目录 一、isinstance与type二、issubclass一、isinstance与type 在游戏项目中#xff0c;我们会在每个接口验证客户端传过来的参数类型#xff0c;如果验证不通过#xff0c;返回给客户端“参数错误”错误码。 这样做不但便于调试#xff0c;而且增加健壮性。因为客户端是可… 目录 一、isinstance与type二、issubclass 一、isinstance与type 在游戏项目中我们会在每个接口验证客户端传过来的参数类型如果验证不通过返回给客户端“参数错误”错误码。 这样做不但便于调试而且增加健壮性。因为客户端是可以作弊的不要轻易相信客户端传过来的参数。 验证类型用type函数非常好用比如 print(type(foo) str) True print(type(2.3) in (int, float)) True 既然有了type()来判断类型为什么还有isinstance()呢 一个明显的区别是在判断子类。 type()不会认为子类是一种父类类型isinstance()会认为子类是一种父类类型。 千言不如一码。 class Foo(object):passclass Bar(Foo):passprint(type(Foo()) Foo) True print(type(Bar()) Foo) False # isinstance参数为对象和类
print(isinstance(Bar(),Foo)) True 需要注意的是旧式类跟新式类的type()结果是不一样的。旧式类都是type instance。 # python2.
class A:passclass B:passclass C(object):passprint(old style class,type(A())) # old style class type instanceprint(old style class,type(B())) # old style class type instanceprint(new style class,type(C())) # new style class class __main__.Cprint(type(A()) type(B())) # True 注意不存在说isinstance比type更好。只有哪个更适合需求。 二、issubclass class Parent:passclass Sub(Parent):passprint(issubclass(Sub, Parent)) True print(issubclass(Parent, object)) True转载于:https://www.cnblogs.com/TankJam/p/11163366.html