shinji
shinji

Reputation: 61

Python, declared object with variable number of attr

I got a problem. I have a array of random elements, and i have object (max array = max attr in object). But if I use:

breadcrumbs = breadObject(element[0],element[1],element[2])

but if i have array with only 2 elements ([0][1]) i got error.

I try with:

  exec("breadcrumbs = breadObject(%s)"%string_bread)
  return breadObject

where string_bread is ex. str("element1","element2") but it return error:

name 'breadObject' is not defined

Upvotes: 0

Views: 74

Answers (1)

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29121

Not sure that understand you correctly but think you can use the following syntax:

breadcrumbs = breadObject(*element)

Arbitrary number of arguments can be collected with *args syntax and an arbitrary number of keyword arguments can be collected as a dictionary with **kwargs syntax.:

def function(*args, **kwargs):
    assert isinstance(args, tuple), 'args is always a tuple'
    assert isinstance(kwargs, dict), 'kwargs is always a dictionary'

*args and **kwargs can be used to call functions with multiple arguments / keyword arguments from a tuple or dictionary

Upvotes: 2

Related Questions