Guido's new method definition idea

Antoine De Groote antoine at vo.lu
Tue Dec 9 06:06:13 EST 2008



anthony.tolle at gmail.com wrote:
> On Dec 6, 4:15 pm, Carl Banks <pavlovevide... at gmail.com> wrote:
[...]
> 
> This brings up another question, what would one use when referencing
> method names inside the class definition?:
> 
> class C:
>     def self.method(arg):
>         self.value = arg
>     def self.othermethod(arg):
>         self.value = arg
>     # do this?
>     funcs = (self.method, self.othermethod)
>     # or this?
>     funcs = (method, othermethod)
> 
> On another related note, I would be interested in seeing this syntax
> adopted for a different purpose...
> 
> Normally, if I'm defining a nested function that needs to be stored as
> an object attribute, I have to use a dummy name, like the following:
> 
> class C:
>     def createfunc(self, arg):
>         def _dummy(arg):
>              return arg + 1
>         self.func = _dummy
> 
> It would be nice to be able to do the following instead:
> 
> class C:
>     def createfunc(self):
>         def self.func(arg):
>             return arg + 1
> 
> Or, after the class definition is done, to extend it dynamically:
> 
> def C.method(self, arg):
>     self.value = arg
> 
> ...which would be the equivalent of the following:
> 
> def method(self, arg):
>     self.value = arg
> C.method = method
> 
> Since functions are first-class objects, it seems perfectly reasonable
> to me.


A decorator might be more advisable here.

class C:
    def createfunc(self):
	@some_decorator_name
        def func(arg):
            return arg + 1

Altough I'm not a huge fan of decorators, this would be more in line
what Python already can do an would lean on the @staticmethod and
@classmethod decorators.



More information about the Python-list mailing list