froadie
froadie

Reputation: 83133

Why can't I access the instance.__class__ attribute in Python?

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?

Upvotes: 0

Views: 3821

Answers (3)

froadie
froadie

Reputation: 83133

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

Upvotes: 3

Matt Anderson
Matt Anderson

Reputation: 19799

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'>

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799190

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

class myClass(object):
    pass

Upvotes: 1

Related Questions