如何在Python中将附加参数与* args一起传递

问题描述

我有一个带有* arg和附加位置参数的函数。但是当调用函数时,我得到以下错误。任何有关如何传递此附加参数的帮助

**error**:
export_bundle() missing 1 required keyword-only argument: 'dict'
from stix2 import MemoryStore,Identity
import datetime

timestamp = datetime.datetime.today().strftime('%Y-%m-%d-%H:%M:%s')

id1 = Identity(
    name="John Smith",identity_class="individual",description="Just some guy",)
id2 = Identity(
    name="John Smith",description="A person",)

dict= {"id":1234,"name":"abd"}

def export_bundle(self,*args,dict):
   mem = MemoryStore()
   for sdo in args:
      mem.add([sdo])
   mem.save_to_file(self.output_location + str(dict['id']) + timestamp+ '.json')
    del mem

export_bundle(id1,id2,dict)

解决方法

您使用可变数量的参数(export_bundle声明了函数*args,因此,如果要在最后定义dict参数,则该参数必须是仅关键字的参数( dict)。如果要传递export_bundle(id1,id2,dict=dict)的值,则可以将其称为dict

def export_bundle(self,*args,dict):
   mem = MemoryStore()
   for sdo in args:
      mem.add([sdo])
   mem.save_to_file(self.output_location + str(dict['id']) + timestamp+ '.json')
   del mem

export_bundle(id1,dict=dict)
,

始终始终使用函数参数,然后是* args,** kwargs

def export_bundle(self,dictm,*args):
   mem = MemoryStore()
   for sdo in args:
      mem.add([sdo])
   mem.save_to_file(self.output_location + str(dict['id']) + timestamp+ '.json')
    del mem```