Using function parameters to determine method kind

Michele Simionato michele.simionato at poste.it
Tue Apr 6 07:09:19 EDT 2004


Lenard Lindstrom <len-1 at telus.net> wrote in message news:<8yh9r7p2.fsf at telus.net>...
> Michele Simionato <michele.simionato at poste.it> wrote:
> >Lenard Lindstrom <len-1 at telus.net> wrote in message
> > news:<4qrzym6e.fsf at telus.net>...
> >> I was wondering if anyone has suggested having Python determine
> >> a method's kind from its first parameter.
>  ...
> >I find relaying on tbe parameter name to specify the kind of method
> >to be rather fragile. It works most times but not always. What about
> >inner classes for instance?
> Do you mean:
>   from dparams import Object
>   class A(Object):
>       class B(Object):
>           def __init__(self, x): self.x = x
>   b=A.B(x)
>  ?

No, I had in mind this (contrived) example:

class Outer(object):
      def outermeth(self1):
          class Inner(object):
                def innermeth(self2):
                    <do-something-with-self1-and-self2>
          ...

It is nice to have the ability to give any name to "self".

> Class A.B is not affected. Parameter checking only happens for
> instances of type function. Other callables have to be or
> use descriptors to be anything other than static. As for B's
> methods, parameter checking works just fine. My module is
> more of a demonstration than a practical solution anyway.
> I would suggest a different approach for implementing
> parameter checking in the python interpreter.
> 
> > Also, there are situations where you want
> >a method to work both with instances and classes, so do you want to
> >use self or cls?
> I can only imagine one way to do this now, wrap the function in a
> descriptor.
> 
> >>> from dparams import Object
> >>> from types import MethodType
> >>> class bimethod(Object):
> ... 	def __init__(self, f): self.f=f
> ... 	def __get__(self, o, t):
> ... 		if o is None: return MethodType(self.f, t, type(t))
> ... 		return MethodType(self.f, o, t)
> ... 	
> >>> class A(Object):
> ... 	def bi(x): return x
> ... 	bi=bimethod(bi)
> ... 	
> >>> A.bi()
>  <class '__main__.A'>
> >>> A().bi()
> <__main__.A object at 0x0119C1B0>
> 
> Descriptors are unaffected by the function's parameters, so the first
> parameter can be anything you want. If I am not mistaken, the only
> methods other that __new__  that currently work without descriptors
> are instance methods. 

?? All methods works with descriptors, what do you mean?
 
> Is it not good form for instance methods to
> start with 'self' anyways? (except maybe for a metaclass's __init__,
> but this is a special case)

It is not a special case (no special case is special enough or something
like that).



More information about the Python-list mailing list