__class__ of what

Eric Brunel eric.brunel at pragmadev.com
Thu Aug 12 10:07:22 EDT 2010


In article 
<72151646-65cb-47bb-bd55-e7eb67577c05 at z10g2000yqb.googlegroups.com>,
 "Eric J. Van der Velden" <ericjvandervelden at gmail.com> wrote:

> Hello,
> 
> I have,
> 
> class C:
>         n=0
>         def __init__(s):
>                 __class__.n+=1
> 
> 
> I do
> >>> C()
> 
> This is fine.

No it's not, at least in Python 2.x:
>>> C()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __init__
NameError: global name '__class__' is not defined

> But of what thing I am taking the __class__ of?

Nothing, precisely. You should write s.__class__ (and replace s by self 
while you're at it).

> I can also do
> 
>         @staticmethod
>         def p():
>                 print(__class__.n)
> 
> >>> C.p()
> 1

No you can't, again in Python 2.x:
>>> C.p()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in p
NameError: global name '__class__' is not defined

Unless I'm missing something or something fundamental changed in Python 
3, your examples do not workŠ

> Thanks,
> 
> Eric J.



More information about the Python-list mailing list