Access from a class attribute

Ben Finney ben+python at
Thu Jun 4 05:24:19 EDT 2009

Kless <jonas.esp at> writes:

> Why can not to access from a class attribute to a function of that
> class?
> -----------------
> class Foo(object):
>    attr = __class__.__name__
>    attr = self.__class__.__name__
> -----------------

The ‘self’ name is not magical. If you want it bound to something, you
have to bind it explicitly; it's exactly like any other name.

You will have noticed this being done in methods of a class:

    class Foo(object):
        attr = 'spam'

        def frobnicate(self, bar):
            self.attr = str(bar)

The statements in the method are evaluated in the context of a specific
call to that method, where the parameters have been passed and bound to
the parameter names.

 \     “I got some new underwear the other day. Well, new to me.” —Emo |
  `\                                                           Philips |
_o__)                                                                  |
Ben Finney

More information about the Python-list mailing list