Zen of Python Classes - Introduction

The neat thing about Python is that it already has enormous utility as a scripting language without people having to worry about writing a single class of their own. This tutorial assumes some knowledge of basic Python, but only an introductory idea of what classes and OOP are. If you are such a beginner, you should find this tutorial to be a very clear and easy intro on how object orientation (OO) in Python works.

If you are coming from 'traditional' OO languages such as C#, C++, Objective-C, and Java though, you should approach this tutorial with a Beginner's Mind and try to discard as much of the stuff you learned from those other languages as possible. Otherwise, your preconceptions might lead to confusion, even if at heart the Python OO approach is really quite simple. One possible exception would be people who are coming from Javascript - because that language shares much of the brevity of Python's OO philosophy and is even more minimalistic in some ways.

The Simplest Python Class

>>> class C: pass

Yes, that's it! And precisely why so many people love this "wrist-friendly" language. In keeping with Zen mind, don't worry about constructors, destructors and all that claptrap for now. Let's just prove to ourselves that we have a class on hand.

One important thing to realize is that the uninstantiated class itself is an object. It is an object and therefore it has a type. It's type is classobj:

>>> type(C)
<type 'classobj'>

Let's instantiate an instance of C and examine it:

>>> i=C()

>>> type(i)
<type 'instance'>
>>> i
<__main__.C instance at 0x0353B990>

i is indeed an instance of C, the latter being found in the __main__ namespace.

Next - Adding attributes to our class

More Python Tutorials