Python调用某个类,传**kwargs参数时,字符串的形式传入方法

Python调用某个类,传**kwargs参数时,字符串的形式传入方法,第1张

Python调用某个类,传**kwargs参数时,字符串的形式传入方法

在调用python的某些类时,事先并不确定参数的,需要自行拼接字符串。解决办法如下,

参考:

https://stackoverflow.com/questions/48838289/pass-string-parameter-into-class-function-pythonhttps://stackoverflow.com/questions/48838289/pass-string-parameter-into-class-function-python

 给出我的代码示例:

# 生成kwargs字符串,比如 host="1", port="2", user="3", password="4", database="5", schema="6", table="7", fileName="8"

kwagrsStr = """host="1", port="2", user="3", password="4", database="5", schema="6", table="7", fileName="8" """


class dataConnector():
    def __init__(self, **kwargs):
        # 主机
        self.host = 'host' in kwargs and kwargs['host'] or None
        # 端口
        self.port = 'port' in kwargs and kwargs['port'] or None
        # 用户名
        self.user = 'user' in kwargs and kwargs['user'] or None
        # 密码
        self.password = 'password' in kwargs and kwargs['password'] or None
        # 数据库
        self.database = 'database' in kwargs and kwargs['database'] or None
        # schema
        self.schema = 'schema' in kwargs and kwargs['schema'] or None
        # table
        self.table = 'table' in kwargs and kwargs['table'] or None
        # fileName
        self.fileName = 'fileName' in kwargs and kwargs['fileName'] or None

    def run(self):
        print(self.host, self.port, self.user, self.password, self.database, self.schema, self.table, self.fileName)


# 引用某个类
dbObject = dataConnector(**eval("dict({})".format(kwagrsStr)))
dbObject.run()

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5690027.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存