multiple values for keyword argument
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sat Jan 29 18:45:02 EST 2011
On Sat, 29 Jan 2011 09:03:28 -0500, Roy Smith wrote:
> In article <8qijsgFgu1U1 at mid.dfncis.de>,
> Frank Dierkes <Frank.Dierkes at googlemail.com> wrote:
>
>> Naming the first parameter self is only a convention. It could be any
>> other name, too.
>
> But it shouldn't. The use of "self" is so universal that using anything
> else will just make your code more difficult for other people to
> understand.
It's a strong convention, true, but for Python to prohibit names other
than self would be a serious mistake. It would add complication to the
parser, for no real benefit. Remember, there's nothing special about
methods. They're just ordinary functions which happen to be passed an
extra argument at runtime. Making it compulsory to call the first
argument "self" would seriously cripple Python's usefulness in at least
three cases.
(1) Class methods receive the class, not the instance, and the convention
is to call that first argument "cls". It would be confusing and
misleading to call it "self".
Similarly, I sometimes use a similar descriptor which combines the
functionality of class methods and ordinary methods. Since neither "self"
nor "cls" would be appropriate, I use the name "this" for the first
argument:
http://code.activestate.com/recipes/577030-dualmethod-descriptor/
Descriptors are a general protocol, so there may be other such
technologies being used by people.
(2) Sometimes people use functions inside a class namespace as an
ordinary function, perhaps as a factory function, called at class
creation time. Here is a toy example that automates the building of
properties:
class K(object):
def build(name): # called at class creation time
def getter(self):
return getattr(self, "_" + name)
def setter(self, value):
setattr(self, "_" + name, value)
return property(getter, setter)
spam = build("spam")
ham = build("ham")
(3) Because methods are just a wrapper around an ordinary function, you
can inject almost any function into a class at runtime. You don't know
what the first argument of that function is called:
>>> class K(object):
... def __init__(self, value='spam'):
... self.attr = value
...
>>> def get_attr(obj):
... return obj.attr
...
>>> k = K()
>>> get_attr(k)
'spam'
>>>
>>> K.method = get_attr
>>> k.method()
'spam'
--
Steven
More information about the Python-list
mailing list