[Tutor] Class vs. instance

Hugo Arts hugo.yoshi at gmail.com
Sun Jan 1 23:03:46 CET 2012

On Sun, Jan 1, 2012 at 8:40 PM, Stayvoid <stayvoid at gmail.com> wrote:
> Hi there!
>>>> class Sample:
>>>>     def method(self): pass
>>>> Sample().method()
> What's the difference between class __main__.Sample and
> __main__.Sample instance?
> Why should I write "Sample().method" instead of "Sample.method"?

The difference can be illustrated as such:

>>> Sample().method
<bound method Sample.method of <__main__.Sample instance at 0x1004d1638>>
>>> Sample().method()
>>> Sample.method
<unbound method Sample.method>
>>> Sample.method()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method method() must be called with Sample instance
as first argument (got nothing instead)

That is, the difference between the methods is that the accessed
through the instance is also attached to that instance. It will
automagically get Sample() passed to it as its first argument (that
would be self). The one attached to the class is unbound, which means
that you can do this:

>>> Sample.method(Sample())

With any Sample instance, of course. This exposes a bit of syntax
sugar in python and how classes are really implemented, essentially
the fact that, if "a" is a sample instance, a.method(arg1, arg2, arg3)
is actually just Sample.method(a, arg1, arg2, arg3)


More information about the Tutor mailing list