Marko Rauhamaa wrote:
Chris Angelico <ros...@gmail.com>:

3) Every invocation of method() has to execute the class body, which
takes time.

That's what happens with every method invocation in Python regardless.

No, it doesn't! Invoking a method involves creating a bound method
object, which is very small and lightweight. Executing a class
statement creates a class object, which is enormous by comparison,
and quite expensive to initialise.

A quick test of your Outer class vs. Chris Angelico's version
suggests that yours is about 12 times slower at creating instances
of Inner.

from timeit import timeit

class Outer1:

    def method(self):
        outer = self
        class Inner:
            def spam(self, a, b):
                outer.quarantine(a, b)
        return Inner()

    def quarantine(self, a, b):
        pass


def test1():
    x = Outer1()
    for i in range(100000):
        y = x.method()
        y.spam(1, 2)


class Outer2:

    class Inner:

        def __init__(self, outer):
            self.outer = outer

        def spam(self, a, b):
            self.outer.quarantine(a, b)

    def method(self):
        return self.Inner(self)

    def quarantine(self, a, b):
        pass


def test2():
    x = Outer2()
    for i in range(100000):
        y = x.method()
        y.spam(1, 2)


t1 = timeit(test1, number = 1)
print("Nested class:    ", t1)

t2 = timeit(test2, number = 1)
print("Non-nested class:", t2)

print("Ratio =", t1 / t2)

----------------------------------------------
Results:
----------------------------------------------
Nested class:     1.899524817999918
Non-nested class: 0.15806536600030086
Ratio = 12.01733729573816

--
Greg
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to