class method question

Bruno Desthuilliers onurb at xiludom.gro
Wed Oct 25 11:59:10 EDT 2006


Sylvain Ferriol wrote:
> hello
> can you explain why python does not see difference between instance
> method and class method, having the same name

Because class namespaces are dicts, and you can't have duplicate keys in
dicts. It's totally unrelated to class/instance method distinction (try
with any kind of attribute, you'll get the same result : only the last
attribute is kept).

> example
>>>> class toto(object):
> ...     def f(self):
> ...             print('instance method')
>
> ...     @classmethod
> ...     def f(cls):
> ...             print('class method')


>>>> t=toto()
>>>> t.f
> <bound method type.f of <class '__main__.toto'>>
>>>> t.f()
> class method
>>>> toto.f()
> class method

Also note that Python classmethods can be called on instances. Here
you're calling the same function twice.

A python object is a data structure holding references to other objects.
One of these references points to a dict (named __dict__) storing the
object's own attributes ('instance' attributes), and another one (named
__class__) points to the class object - which is itself an object that
holds references to it's parent classes.

When a name is looked up on an object, the name is first looked up in
the object's __dict__, then in the class, then in the class's parent
classes...

If you want a Ruby-like behaviour, it's still possible, but you have to
do it by manually:

import types

class Rubysh(object):
    @classmethod
    def test(cls):
        print "in classmethod test, cls : %s" % cls

    def __init__(self):
        def test(self):
            print "in instance method test, self : %s" % self
        self.test = types.MethodType(test, self, self.__class__)

Rubysh.test()
r = Rubysh()
r.test()

Also note that most python programmers may find this a bit confusing,
since they'd expect Rubish.test() and r.test() to resolve to the same
attribute...

> 
> if i do the same in ruby:

You're not "doing the same", you're doing something that *looks* the same.

While they look quite similar at first sight - and indeed share a lot of
characteristics (lightweight, highly dynamic, hi-level object languages)
-, Python and Ruby are very different beasts under the hood. So beware :
superficial similarities can hide very different meanings and behaviours.

HTH
-- 
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