[Tutor] Understanding Classes

eryksun eryksun at gmail.com
Tue Jan 21 16:14:42 CET 2014


On Tue, Jan 21, 2014 at 7:18 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> The same applies to methods, with just one additional bit of magic: when
> you call a method like this:
>
>      instance.method(a, b, c)  # say
>
> Python turns it into a function call:
>
>      method(instance, a, b, c)
>
> [For advanced readers: to be precise, Python uses what is technically
> known as an *unbound method*, which it gets by looking inside the class
> of `instance`. To be even more precise, in Python 3, it no longer uses
> unbound methods but just regular functions. But the basic concept is
> the same.]

You're using 2.x but didn't subclass `object`. Old-style classes
behave differently in many cases, starting with the most basic
difference:

    >>> type(my_car)
    <type 'instance'>

If you're targeting both 2.x and 3.x, remember to subclass `object` explicitly.

A minor correction about methods: it's a "bound" method:

    >>> my_car.start_engine.__self__ is my_car
    True

The wrapped function is `__func__`:

    >>> type(my_car.start_engine.__func__)
    <type 'function'>
    >>> my_car.start_engine.__func__.__name__
    'start_engine'


More information about the Tutor mailing list