我正在尝试运行函数 Order
,它有 2 个版本,一个函数是 client.LinearOrder.LinearOrder_new(side="Buy",symbol=tradingpair,order_type="Market",qty=1).result()
,如果关键字“USDT”存在于 Pair
中,否则它执行 client.Order.Order_new(side="Buy",symbol=tradingpair,order_type="Market",qty=1).result()
.当 Order_Execution
被拆分为两个 Order
时,getattr
函数按预期工作,我试图在不拆分的情况下运行它,我将如何修改下面的代码以使其正常工作。< /p>
工作代码:
def Exec(Pair)
Order_Execution = "LinearOrder" if "USDT" in tradingpair else "Order"
Order_Execution2 = "LinearOrder_new" if "USDT" in tradingpair else "Order_new"
Order = getattr(getattr(client, Order_Execution), Order_Execution2)(side="Buy",symbol=tradingpair,order_type="Market",qty=1).result()
Exec("BTCUSD")
无功能代码:
def Exec(Pair)
Order_Execution = "LinearOrder.LinearOrder_new" if "USDT" in tradingpair else "Order.Order_new"
Order = getattr(client, Order_Execution)(side="Buy",symbol=tradingpair,order_type="Market",qty=1).result()
Exec("BTCUSD")
答案 0 :(得分:0)
您只能拆分它们。第二个参数:
getattr(obj, attr)
是对象的属性名称。由于有效的 Python 标识符不能包含点,因此您无法运行的代码只会失败。
你为什么不把问题简单化?除了使用 getattr()
,您可以:
def Exec(Pair):
if "USDT" in tradingpair:
Order_Execution = client.LinearOrder.LinearOrder
else:
Order_Execution = client.Order.Order_new
Order = Order_Execution(side="Buy",symbol=tradingpair,order_type="Market",qty=1).result()
Exec("BTCUSD")
注意:函数 Pair
的参数 Exec
未使用。