Defining a Class
You need to group together related data and functionality into a class.
Define a class and provide it with the member variables you need.
The following example defines a class to represent an address book entry:
class Person: ”’This class represents a person object”’ def __init__(self, name, tel): self.name = name self.tel = tel |
The first line inside the class definition uses the triple, single, or double quotes to denote a documentation string. This should explain the purpose of the class. Although entirely optional, adding a documentation string to a class allows others to see what the class does. This is particularly useful if the class is made available for others to use.
Doc strings are not like normal comments because, although they are not active lines of code, they do get associated with the class, so, at any time, you can read the doc string for a class using the following command:
Person.__doc__ |
Inside the class definition is the constructor method, which will be called automatically whenever you create a new instance of the class. A class is like a template, so in defining a class called Person, we do not create any actual Person objects until later:
def __init__(self, name, tel): self.name = name self.tel = tel |
The constructor method must be named as shown with double underscores on either side of the word init.
Discussion
One way in which Python differs from most object-oriented languages is that you have to include the special variable self as a parameter to all the methods that you define within the class. This is a reference to, in this case, the newly created instance. The variable self is the same concept as the special variable this that you find in Java and some other languages.
The code in this method transfers parameters that were supplied to it into member variables. The member variables do not need to be declared in advance, but do need to be prefixed by self..
So the following line:
self.name = name |
creates a variable called name that’s accessible to every member of the class Person and initializes it with the value passed into the call to create an instance, which looks like this:
p = Person(“Simon”, “1234567”) |
We can then check that our new Person object, p, has a name of “Simon” by typing the following:
>>> p.name Simon |
In a complex program, it is good practice to put each class in its own file with a filename that matches the class name. This also makes it easy to convert the class into a module (see Recipe 7.11).
See Also
See Recipe 7.5 for information on defining methods.