Another try at Python's selfishness

bruno at modulix onurb at xiludom.gro
Fri Feb 3 10:09:25 EST 2006


n.estner at gmx.de wrote:
> Having read previous discussions on python-dev I think I'm not the only
> Python programmer who doesn't particularly like python's "self"
> parameter:

bang ! You're dead !

(no no, just kidding !-)

> 
>     class Foo:

old-style classes are deprecated.

class Foo(object):

>         def bar(self, a,b):
>             return a+b


(snip)

> The point is, I _do_ think it's a good idea to explicitly write
> "self.SomeMember" for member-access,

With Python's lookup rules, it couldn't be otherwise anyway !-)

> so I thought: why can't we be
> equally explicit about member function declaration?

Because there's no such thing as a "member function" in Python.

> Wouldn't it be nice
> if I could write (say, in Python 3k, or maybe later):
> 
>     class Foo:
>         def self.bar(a,b):
>             return a+b
>     Foo().bar(1,2) => 3

'bar' is not an instance attribute, but a class attribute - it belongs
to *class* Foo, not to an instance of Foo.

BTW, 'self' does not yet exist (and cannot possibly exist) when this
code is eval'd (how could an instance of class Foo exists before class
Foo itself exists ?).

> That way, the declaration would match the invocation (at least
> syntactically), and the "magic"-feeling is gone. In the long run, the
> "old-style" syntax (i.e. if there's no '.' in the method name) could be
> used for static methods.

s/static/class/

> What do you think?

That you should learn more about the inners of Python's object model
(and specially at the Descriptor protocol).

class Foo(object):
  def __init__(self, a):
    self.a = a

def bar(obj, b):
 return obj.a + b

f = Foo(1)
bar(f, 2)

Foo.bar = bar
Foo.bar(f, 2)
f.bar(2)

The only 'magic' here is that when bar() is called *as an attribute of a
Foo instance*, the instance is passed as the first parameter. In fact,
this is much more explicit (well, IMHO) than the 'this' reference in
Java or C++.



-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list