In most object-oriented languages, objects are created in two steps: First, the object is constructed, and second, the object is initialized. Some languages merge these two steps into one, but Python keeps them separate. Python has the_new_() special method which is called to construct an object, and the
_init_() special method which is called to initialize a newly constructed object. It is very rare to actually need to implement_new_() ourselves; not one of the custom classes in this book needs it—and older versions of Python did not even have the_new_() special method. Python is perfectly capable of constructing our objects for us, so in almost every case the only method we need to implement is_init_().
In view of Python's two-step object creation, we will normally talk of object creation rather than construction. Also, we will generally refer to a class's initializer (its_init_() method), since that is the method that is normally reimplemented in custom classes and the one that is closer to the idea of a constructor that is used in languages like C++ and Java.
Let's see how to create a class in practice. We will create one that stores a string (the name of a kind of chair) and a number (how many legs the chair has):
This class represents chairs
self.name = name self.legs = legs
It is conventional to follow a class statement with a docstring as shown in the preceding code. We will not normally show docstrings in the book, but they are included where appropriate in the accompanying example code. The blank line is purely for aesthetics and clarity.
Methods with names beginning and ending with two underscores are "special" methods. Python uses such methods to integrate custom classes so that they can have the same usage patterns as built-in classes, as we will soon see.
The_init_() method, and indeed every method, has a first parameter that is the Python equivalent to the C++ or Java "this" variable, that is, a variable that refers to the object itself. This variable is conventionally called self. We must put self as the first item of every (nonstatic*) method's parameter list, although we never need to pass it since Python will do that for us.
Although the name "self" is merely conventional, we will always use it. Inside the object, we must use self explicitly when we want to refer to instance methods or attributes. For example, in the Chair class's initializer, we have created two data attributes using self. Thanks to Python's dynamic nature, it is possible to create additional attributes in other methods, and even to add additional attributes to particular instances if we wish; but we will take a more conservative line that is sufficient for the GUI programming we are working toward.
To create an instance of a class, we use the following syntax:
instance = className(arguments)
The parentheses are mandatory, even if we don't pass any arguments. Behind the scenes, Python constructs the object by calling the class's static_new_()
method (which is inherited from object, or in rare cases is implemented by us), and then calls_init_() on the newly constructed object. The resulting initialized object is returned.
In the case of our Chair class, we must pass either one or two arguments (Python passes the first self argument automatically for us); for example:
chair1 = Chair("Barcelona") chair2 = Chair("Bar Stool", 1)
Since the attributes are public, they can be read or assigned to using the dot (.) operator;for example: print chair2.name will print "Bar Stool", and chair1.legs = 2 will change chair1's legs attribute's value from 4 to 2.
Object-oriented purists will no doubt be uncomfortable with this kind of direct access to attributes from outside the instance, whereas those with a taste for extreme programming may be perfectly happy with it since we can always add accessor methods later.
Now that we have seen how construction and initialization are handled, we need to consider object destruction. C++ programmers are used to using destructors and relying on the fact that they can delete objects at a time of their own choosing. Java and Python programmers do not have that particular luxury. Instead, they have automatic garbage collection, which makes programming much easier in general but with the one drawback of not giving fine control over exactly when objects are deleted. If resources need to be protected, the solution is normally to use a try ... finally block to guarantee cleanup.
When an object is about to be garbage-collected its_del_() special method is called, with self as its only argument. As is common practice in Python (and in Java regarding the finalize() method), we very rarely use this particular special
*A static method is one that can be called on a class or an instance and has no self parameter. Normal methods are non-static, that is, they have a self parameter and must be called on instances.
method. To put this in perspective, out of more than 170 classes in this book's examples and exercise solutions, not one reimplements_del_().
We have now learned how to create and initialize an object of a custom class. Next, we will see how to provide additional methods to give our class distinctive behavior. We will also learn how to ensure that our classes smoothly integrate with the rest of Python, and act just like built-in classes where that is appropriate.
Was this article helpful?
Video Marketing Will Never Be The Same Again. Here's How YOU - Or ANYONE - Can Leverage On The Internet's 4th MOST TRAFFICKED WEBSITE TO BOOST YOUR POPULARITY amp PUBLICITY FOR BUSINESS via Video Marketing! With The Emergence Of Web Video Popularity, You CANNOT Afford To Miss Out On This Exponentially Growing Trend - Because It Could Make Or Break Your Popularity amp Business Growth!