zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    【模拟练习】[一]
    【搜索练习】【二】
    【搜索练习】【一】
    模板整理 (施工中 2017.8.30更新)
    常用STL整理 (施工中 2017.8.11更新)
    剑指Offer 反转链表
    剑指Offer 链表中倒数第k个结点
    剑指Offer 斐波那契数列
    剑指Offer 用两个栈实现队列
    剑指Offer 从尾到头打印链表
  • 原文地址:https://www.cnblogs.com/laosun0204/p/8591064.html
Copyright © 2011-2022 走看看