在调用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()

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐