0

I'm new to Python, and I know I must be missing something pretty simple, but why doesn't this very, very simple code work?

class myClass:
    pass

testObject = myClass
print testObject.__class__

I get the following error:

AttributeError: class myClass has no attribute '__class__'

Doesn't every object in Python have a __class__ attribute?

froadie
  • 79,995
  • 75
  • 166
  • 235
  • Error only exists in Python 2.x. In Python 3.1 the `__class__` does not generate an error. And, why are you still using old-style class? – kennytm May 14 '10 at 16:02
  • @KennyTM - this might be dense but... what are old style classes? – froadie May 14 '10 at 16:09
  • Classes which don't derive from `object`. – kennytm May 14 '10 at 16:13
  • @KennyTM - in Python, are you supposed to explicitly derive all classes from object? (And if so, why?) – froadie May 14 '10 at 16:15
  • All new-style classes should derive from `object` in the top level. See http://stackoverflow.com/questions/54867/old-style-and-new-style-classes-in-python for detail. – kennytm May 14 '10 at 19:04

3 Answers3

3

I think I realized my mistake. I thought that the code testObject = myClass was creating a new instance/object of the class, but it was actually assigning a reference to the class itself. I changed the code to:

class myClass: 
    pass 

testObject = myClass() 
print testObject.__class__ 

and it now works as I was expecting

froadie
  • 79,995
  • 75
  • 166
  • 235
2

Most, but not all, objects in Python have a __class__ attribute. You can usually access it to determine an object's class.

You can get the class of any object by calling type on it.

>>> class myClass:
...     pass
... 
>>> testObject = myClass
>>> type(testObject)
<type 'classobj'>
Matt Anderson
  • 19,311
  • 11
  • 41
  • 57
1

Old-style classes don't have a __class__ attribute.

class myClass(object):
    pass
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358