day10_hasattr和getattr、setattr、delattr和property的用法

class My:
    def __init__(self, x=0):
self.x = x

my = My()
# hasattr判断对象(my)是否有'x'属性,打印True or False,只能是'x',不能是x
print(hasattr(my, 'x')) # 打印出True
# 从对象中获取'x'属性
print(getattr(my, 'x')) # getattr打印出0
print(getattr(my, 'y')) # 报AttributeError: 'My' object has no attribute 'y'错误
print(getattr(my, 'y', 'hello')) # 打印出hello,如果不给个默认值就会报错,没有y属性
# setattr是给指定对象的属性设置一个值
setattr(my, 'z', 'test')
print(getattr(my, 'z')) # 打印出test
# delattr是删除指定对象的属性,没有返回值
delattr(my, 'x')
delattr(my, 'x') # 报AttributeError: x,因为已经删除过了,再删就报错了
 
 

import requests


class MyRequest:
def __init__(self, url, method='get', data=None, headers=None, is_json=None):
method = method.lower()
self.url = url
self.data = data
self.headers = headers
self.is_json = is_json
if hasattr(self, method): # 判断某个对象有没有某个方法,有打印True,没有打印False
getattr(self, method)() # 根据字符串调用对应的方法

def get(self): # 无论正常还是异常返回的都是一个字典
try:
req = requests.get(self.url, self.data, headers=self.headers).json()
except Exception as e:
self.response = {"error": "接口请求出错%s" % e}
else:
self.response = req

def post(self):
try:
if self.is_json:
req = requests.post(self.url, json=self.data, headers=self.headers).json()
else:
req = requests.post(self.url, self.data, headers=self.headers).json()
except Exception as e:
self.response = {"error": "接口请求出错%s" % e}
else:
self.response = req

if __name__ == '__main__':
login = MyRequest('http://127.0.0.1:5000/login', data={'username': 'ssj', 'password': '123456'})
print(login.response)
session_id = login.response.get('session_id')
data = {'session_id': session_id, 'money': 10000}
m = MyRequest('http://127.0.0.1:5000/pay', data=data)
print(m.response)
posted @ 2018-03-17 17:16  laosun0204  阅读(206)  评论(0编辑  收藏  举报