Monday, September 6, 2010

Classes in Python

In Python, "classes are objects too". Let me clarify.

Let me define a sample class.
>>> class abc: pass
>>> abc
< at 0xb76e341c>
It indicates that in Python, classes are not abstract!
They too take memory space.

Lets explore further.
>>> m = abc
>>> m
< at 0xb76e341c>
>>> m = abc( )
>>> m
< instance at 0xb76e298c>
i.e, in Python, both classes and their objects are concrete.

>>> abc.p = 10
>>> abc.p
Classes can act as objects, as already told above!

Still further,
>>> m = abc()
>>> m.p
>>> m.q = 20
>>> abc.q
What exactly happened here?

Things to understand:
1. Here, "." works as a search operator 
2. On querying m.p, first checks if there's a p attribute in m
3. If not, automatically finds out type of m, then searches for p there.
4. The p attribute here, actually belongs to abc, not m.

No comments:

Post a Comment