https://blog.csdn.net/weixin_45912307/article/details/115535043
动态传参方式1:python反射
1. setattr(对象,属性名,值)
:设置属性值 对象.属性名 = 值,对象为类对象或函数对象
def setattr(x, y, v): # real signature unknown; restored from __doc__
"""
Sets the named attribute on the given object to the specified value.
setattr(x, 'y', v) is equivalent to ``x.y = v''
"""
pass
2. hasattr(对象,属性名)
:判断是否有这个属性
def hasattr(*args, **kwargs): # real signature unknown
"""
Return whether the object has an attribute with the given name.
This is done by calling getattr(obj, name) and catching AttributeError.
"""
pass
3. getattr(对象, 属性名, 默认值=None)
:获取对象属性值,如果指定了默认参数,则在属性没有指定时返回该参数;当返回的参数不存且没有给定默认参数,在这种情况下会抛出异常。
"""
getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case.
"""
pass
4. delattr(对象,属性名)
:删除一个对象属性
def delattr(x, y): # real signature unknown; restored from __doc__
"""
Deletes the named attribute from the given object.
delattr(x, 'y') is equivalent to ``del x.y''
"""
5. 案例
# -- encoding: utf-8 --
# @time: 2021/4/8 23:39
# @Author: jsonLiu
# @Email: xxxxxxxx@qq.com
# @file: globalvariable
class GlobalMap:
Cookie = None
setattr(GlobalMap,'Cookie','123456')
print(hasattr(GlobalMap,'Cookie')) # True
print(getattr(GlobalMap,'Cookie')) # 123456
delattr(GlobalMap,'Cookie') #删除这个属性
动态传参方式2:context上下文管理
将项目当中要使用的所有临时变量存储到context当中
# 使用类属性/函数的方式
import random
class Context:
Authorization = ''
member_id = None
noExist_memberId = None
mobile_phone = "13888888889"
pwd = 123456789
def generate_member_id():
# 生成数据库中不存在的用户id
member_id = random.randint(100000, 999999)
Context.noExist_memberId = member_id
def save_token():
json_data = login()
member_id = jsonpath(json_data, '$..id')[0]
token_type = jsonpath(json_data, '$..token_type')[0]
token = jsonpath(json_data, '$..token')[0]
Authorization = " ".join([token_type, token])
Context.Authorization = Authorization
Context.member_id = member_id