1

Let's say I have a function assigned to a variable, func. func contains the function itself (ie. print func returns <function func at 0x103f25410>

I have a simple class:

class Item():
    def __init__(self, data):
    # init code
        pass
    def func(self):
        pass
    def dunc(self):
        pass

Let's say in __init__ I received func in data and can access it as data.func. I could assign that to consume by self.consume = data.func.

But what if I had a dictionary of functions in data?

{"func" : <function func at 0x103f25410>, "dunk" : <function dunk at 0x103f25410>}

Is there anyway I could do something like self.key = data[key]? In other words, assign func and dunc with the data in the dictionary but not explicitly have to self.func or self.dunc every assignment?

1 Answer 1

2

If I understand your question correctly, you could do something like:

def __init__(self, data):
    for name, func in data.items():
        setattr(self, name, func)

Then, you can refer to self.func or self.dunc (or whatever else was in data).

Sign up to request clarification or add additional context in comments.

1 Comment

You're welcome, sorry about the confusion on the setattr() call. I blame this flu I've got. :)

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.