[PYTHON] Dynamically declare class like a closure

For example, if you declare class-based-view in django, it's a similar class. Regardless, it's a hassle to declare each time! Is there something like that? I have.

So, there is something called a "closure function" around there. An example is below. In Python, you can write as below.

python


# -*- coding: utf-8 -*-


def closure_factory(number):
    def _closure(some_integer):
        return number * some_integer
    return _closure


def closure_test():

    for x in range(10):
        func = closure_factory(x)
        for y in range(10):
            print func(y)


if __name__ == '__main__':
    closure_test()

In this case, abstract it in the form of "function to multiply by n", actually create "how many times the function is needed" with closure_factory, and then execute it. It is in shape.

I don't know because I haven't seen the behavior of Python in detail, but it seems that the class is generated at the "declared timing". Therefore, it is also possible to declare a class like a closure in the form below.

python


# -*- coding: utf-8 -*-


def testfactory(hoge):

    class TestClass(object):
        number = hoge

        def say(self):
            print self.number

    return TestClass


def main():

    for x in range(30):
        klass = testfactory(x)
        klass().say()

What makes me happy when I create a class factory like this is that when I create a class where I only need to change some parameters, I don't have to declare it one by one, so I declare only the changed parts of the parameters. The advantage is that you can get better just by giving it (probably).

However, on the other hand, if this Factory is called many times, what will happen to the processing performance may be burdensome, so it may depend on the timing of use.

Recommended Posts

Dynamically declare class like a closure
Profile within a class method
[Road to Python Intermediate] Call a class instance like a function with __call__