如何在Python中传递附加参数和*args

2024-06-01 06:53:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个接受*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",
    identity_class="individual",
    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)

Tags: 函数nameimport参数datetimeexportjohnmem
2条回答

始终先选择功能参数&;然后*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```

您使用可变数量的参数(*args)声明了函数export_bundle,因此如果要在末尾定义dict参数,则它必须是纯关键字参数(dict)。如果要传递dict的值,可以将其称为export_bundle(id1, id2, 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, id2, dict=dict)

相关问题 更多 >