class scope questions
Alex Martelli
aleaxit at yahoo.com
Fri Feb 9 06:58:13 EST 2001
"Ben de Luca" <c941520 at alinga.newcastle.edu.au> wrote in message
news:3a83bea8$0$16388$7f31c96c at news01.syd.optusnet.com.au...
> 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):
print self.dog
x = A()
x.blah()
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* self.dog, 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 A.dog for reading, A.dog='buh' for writing;
or, getattr(A,'dog') for reading, setattr(A,'dog','buh')
for writing.
Alex
More information about the Python-list
mailing list