1

I want to create a generic function that takes as argument different kind of objects which have different types of parameters, like this :

def func(obj, param, param_values):
    for param_value in param_values:
        obj.setParam(param=param_value)
        # do some stuff
    end

Now I would like to call that function with different objects, which take different parameters names, as such:

func(obj1(), width, {1,2,3,4})
func(obj2(), height, {4,5,6})

However, when I write it this way, I have an error saying that 'param' is not a parameter of obj1 and obj2.

How can I write my function such that it's the value of 'param' that is read and not the word 'param'? Same goes for 'param_value' as I'm anticipating that it could lead to the same problem.

3 Answers 3

1

Use setattr to add attributes to objects.

For example:

class Foo:
    def __init__(self):
        self.a = "hi"

foo = Foo()
foo.a # "hi"

def func(obj, param, param_values):
    setattr(obj, param, param_values)

func(foo, "b", [1,2,3])

foo.b # [1,2,3]
Sign up to request clarification or add additional context in comments.

Comments

1

I think you're looking for the setattr function.

E.g:

def func(obj, param, param_values):
    for param_value in param_values:
        setattr(obj, param, param_value)
        # do some stuff
    end

Comments

0

You can add a variable number of arguments to an object with **kwargs and setattr.

class Foo:
    def __init__(self):
        pass

def func(obj, **kwargs):
    for k,v in kwargs.items():
        setattr(obj,k,v)

foo = Foo()

func(foo, width={1,2,3,4}, height={4,5,6})

print("width: {}".format(foo.width))
print("height: {}".format(foo.height))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.