python错误总结(常更)

python错误总结(常更)

AttributeError: ‘set’ object has no attribute ‘items’ 出错原因是在http请求的header里,应该用冒号而不是逗号//wrongheaders={ ‘Content-Type’, ‘application/json’ }//okheaders={ ‘Content-Type’: ‘application/json’ }

//wrongheaders={ ‘Content-Type’, ‘application/json’ }//okheaders={ ‘Content-Type’: ‘application/json’ }

2.TypeError: not enough arguments for format string 出错原因是在占位符替换时的替换对象,应该是一个元组

//wrongkey = ‘%s-%s-%s’ % report_date[0:4], report_date[4:6], report_date[6:]//okkey = ‘%s-%s-%s’ % (report_date[0:4], report_date[4:6], report_date[6:])

//wrongkey = ‘%s-%s-%s’ % report_date[0:4], report_date[4:6], report_date[6:]//okkey = ‘%s-%s-%s’ % (report_date[0:4], report_date[4:6], report_date[6:])

3.dict is an unmarshal type 出错原因是 requests包的post请求data必须放一个json化好的数据,而不是数据本身

buf = {‘username’:’fw’}//wrongrequest.post(‘www.baidu.com’,headers={‘Content-Type’:’application/json’},data=buf)//okrequest.post(‘www.baidu.com’,headers={‘Content-Type’:’application/json’},data=json.dumps(buf))

4.‘dict’ objectt has no attribute ‘x’ 出错原因: 平时写go时,{}指代的就是对象,而python里{}指代字典,字典的成员访问不存在点.,只有对象可以通过点.访问成员

obj = {‘username’:’fwe’}# wrongprint(obj.username)# okprint(obj.get(‘username’))print(obj.get(‘username’,”))print(obj[‘username’])

相比之下,python里的对象长这样:

class T: __init__(self,arg): this.arg =arg

# 使用时 t = T(‘xxx’) print(t.arg)

还有其他区别比如: print(t)和print(obj) 前者输出Object(T),后者输出{‘username’:‘fwe’} type(t)和type(obj) 这个输出也是不同的,答案就不说了自己测测

5.关于时间类型的格式化失效的问题 正确的写法和错误的写法:

# wrongprint(datetime.today().strftime(‘%y-%m-%d %H:%m:%s’))

# okprint(datetime.today().strftime(‘%Y-%m-%d %H:%M:%S’))

6.去除字符串两边空格

# wrongstr.strip(‘ time ‘)

# ok’ time ‘.strip()

7.获取body,param,query三种参数

@action(methods=(‘get’,), detail=False, url_path=’invite/relative’)def get_invite_relative(self, request, *args, **kwargs): # query www.baidu.com?keyword=xxx keyword = request.query_params.get(‘keyword’, ”) # body {‘name’:’ft’} name = request.data.get(‘name’,”) # param invite/:id/relative id = kwargs[‘id’]

8.时间转换:

# reg_time是date或者datetime类型row.reg_time.strftime(‘%Y-%m-%d %H:%M:%S’),# reg_time是string类型parser.parse(reg_time).strftime(‘%Y-%m-%d %H:%M:%S’)

9.整型除法和地板除法

print(2/8) # 0.25print(2//8) # 0​​execute() takes from 2 to 3 positional arguments but 5 were given​​​ 原因是 cursor.execute(sql, arg1,arg2,arg3) 这样写是错误的 应该写成 cursor.execute(sql, [arg1, arg2, arg3])打日志:import loggingimport logging.config… logging.basicConfig(level=logging.DEBUG, format='[%(asctime)s] %(levelname)s [%(funcName)s: %(filename)s, %(lineno)d] %(message)s’, datefmt=’%Y-%m-%d %H:%M:%S’, filemode=’a’) logging.error(info) logging.info(msg)通过反射拿到class内部字段,如何区分函数和字段def IfFunc(obj): return hasattr(obj,’__call__’)


比丘资源网 » python错误总结(常更)

发表回复

提供最优质的资源集合

立即查看 了解详情