首页 > 解决方案 > Python:动态实例化

问题描述

我需要使用对象变量来减少代码行和复杂性。这是我将要使用的代码:

exchange = ccxt.binance({
        'apiKey': 'YOUR_API_KEY',
        'secret': 'YOUR_SECRET',
        'enableRateLimit': True,
    })

我需要使binance零件动态化,因为在这种情况下可能有几百种不同的东西。有没有简单的方法可以做到这一点?

提前致谢。

标签: pythondynamicinstantiation

解决方案


如果你想每次调用不同的方法,你可以使用:

try:
    # get a method and choose it's name runtime
    yourMethod = getattr(ccxt, 'binance')
    # call it
    yourMethod({
        'apiKey': 'YOUR_API_KEY',
        'secret': 'YOUR_SECRET',
        'enableRateLimit': True,
    })
catch AttributeError:
    print "method with that name doesn't exist"

推荐阅读