Defining new types with classes

You can get a long way in Python using the built in scalar and collections types. For many problems the built in types, together with those available in the Python Standard Library, are completely sufficient. Sometimes though, they aren't quite what's required, and the ability to create custom types is where classes come in.

As we've seen, all objects in Python have a type, and when we report that type using the type() built-in function the result is couched in terms of the class of that type:

>>> type(5)
<class 'int'>
>>> type("python")
<class 'str'>
>>> type([1, 2, 3])
<class 'list'>
>>> type(x*x for x in [2, 4, 6])
<class 'generator'>

A class is used to define the structure and behaviour of one or more objects, each of which we refer to as an instance of the class. By and large, objects in Python have a fixed type from the time they are created – or instantiated – to the time they are destroyed. It may be helpful to think of a class as a sort of template or cookie-cutter used to construct new objects. The class of an object controls its initialization and which attributes and methods are available through that object. For example, on
a string object the methods we can use on that object, such as split(), are defined in the str class.

Classes are an important piece of machinery for Object-Oriented Programming (OOP) in Python, and although it's true that OOP can be useful for making complex problems more tractable, it often has the effect of making the solution to simple problems unnecessarily complex. A great thing about Python is that it's highly object-oriented without forcing you to deal with classes until you really need them. This sets the language starkly apart from Java and C#.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset