class scope questions

Alex Martelli aleaxit at
Fri Feb 9 06:58:13 EST 2001

"Ben de Luca" <c941520 at> wrote in message
news:3a83bea8$0$16388$7f31c96c at
> if i do this
> class a:
>          dog='woof'
>           def blah():
>                     something

...then you're doing it wrong, because a method such as
blah should always have at least one argument.  The first
argument of a method is invariably called 'self', by
near-universal Python convention; it is bound to the
object on which the method is being called.

(Another popular convention is to name classes with a
name starting with an uppercase letter).

> how do i call a

You call a this way:

x = a()

this instantiates an instance of class a, and binds
variable x to said instance.

> how do i get soemthing in blah to refernce dog? either to read it or write
> to it

The normal approach to _reading_ a class-attribute is to
reference it as an attribute of self:

class A:
    dog = 'woof'
    def blah(self):

x = A()

this will print 'woof'.  Since the instance does not directly
have an attribute named dog, the class's dictionary is looked
up for it, so the class-attribute is found.

However, if you *assign*, then that will bind a
(possibly new) attribute called 'dog' *in the instance*, and
NOT affect the _class_ attribute similarly named.  If you
do want to ensure you're accessing the class attribute,
you can use for reading,'buh' for writing;
or, getattr(A,'dog') for reading, setattr(A,'dog','buh')
for writing.


More information about the Python-list mailing list