1

(This is in Python 3 btw)

Okay so say we use type() as a class constructor:

X = type('X', (), {})

What I'm trying to find is how would type() accept a function as an argument and allow it to be callable?

I'm looking for an example of how this could be accomplished. Something along the lines of:

>>> X = type('X', (), {'name':'World', 'greet':print("Hello {0}!".format(name))}
>>> X.greet()
Hello World!
2
  • What does this have to do with dynamic programming? Commented Oct 16, 2016 at 7:28
  • @juanpa.arrivillaga my overall project has to do with dynamic programming. I chose tags revolving around the main purpose behind the question so I would attract those who could answer with that mindset. Commented Oct 16, 2016 at 8:30

1 Answer 1

2

You need to pass the function. In your code, you call the function, and pass the result.

Try:

def print_hello(self):
    print("Hello {0}!".format(self.name))

X = type('X', (), {'name':'World', 'greet': print_hello})
Sign up to request clarification or add additional context in comments.

1 Comment

Oh so the function needs to be defined beforehand? That helps with that part, now I've gotta find a way to dynamically define a function. most likely with eval() i'm sure

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.