Lambda forms and scoping

Márcio Faustino m.faustino at gmail.com
Thu Mar 19 22:52:31 CET 2009


Hi,

Executing the example below doesn't produce the expected behavior, but
using the commented code does. Is this normal, or is it a problem with
Python? I've tested it with version 2.6.1 on Windows XP.

Thanks,

--

from abc import *
from types import *
import re

class Base (ObjectType):
    __metaclass__ = ABCMeta

    def __init__(self):
        for option in self.get_options().keys():
            method = 'get_%s_option' % re.sub(' ', '_', option.lower
())
            setattr(self.__class__, method, lambda self:
self.get_option(option))

        #def create_method(option):
        #    method = 'get_%s_option' % re.sub(' ', '_', option.lower
())
        #    setattr(self.__class__, method, lambda self:
self.get_option(option))
        #
        #map(create_method, self.get_options().keys())

    @abstractmethod
    def get_options(self):
        raise NotImplementedError()

    def get_option(self, option):
        return self.get_options()[option]

class Derived (Base):
    def get_options(self):
        return {
            'Message': 'Hello world!',
            'Web site': 'http://www.example.com',
        }

object = Derived()
print object.get_message_option()
print object.get_web_site_option()



More information about the Python-list mailing list