• 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)
  • 相关阅读:
    用Sqoop实现数据HDFS到mysql到Hive
    hdfs的文件结构
    搭建Hadoop-1.2.1&hbase-0.94.17&hive-0.9.0&centos6.8_x64集群
    缩减表空间碎片
    MySQL8.0.12源码编译安装_centos7.3
    Mysql8.0.18的源码安装
    mysql5.7.31二进制安装_centos7
    个人windows开发环境风格
    linux shell中那些奇奇怪怪的语法
    关于上线的一些事儿
  • 原文地址:https://www.cnblogs.com/laosun0204/p/8591064.html
Copyright © 2020-2023  润新知