Search code examples
pythonpython-3.xdynamic-programmingmetaclassclass-method

How do you define a function during dynamic Python type creation


(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!

Solution

  • 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})