A Smooth Refresher on Python’s Classes and Objects
Python comes with many built-in data types, such as dict, list, set, etc. Have you ever wondered if you can create your own data types? Like
university, etc.? Would creating such data types be possible? Yes, that is certainly possible in Python, and this is where classes and objects come into play.
In this tutorial, I'm going to describe what is meant by a class and an object, and how we can work with them in Python.
Classes and Objects
As mentioned above, classes and objects are about creating your own data type (i.e. user-defined data types). A class is thus a user-defined data type, and creating instances of a class (instantiation) means creating objects of that type. At the end of the day, classes and objects are considered the main building blocks for Python, which is an object-oriented programming language.
What would it be like to create a class in Python? The simplest class structure in Python looks as follows:
class ClassName: statements
As you can see, defining a class starts with the
class keyword, and
className is the name of the class (identifier). Keep in mind that the class name follows the same rules as variable names in Python, that is the name can only start with a letter or underscore
_, and can only contain letters, numbers. or underscores. Also, referring to PEP 8 (Style Guide for Python Code), we can see that it is recommended to name classes in CapWords (upper CamelCase) style.
Let's now define a class
Person, which at the moment will not contain anything, except the
pass statement. As mentioned in Python's documentation:
passstatement does nothing. It can be used when a statement is required syntactically but the program requires no action
class Person: pass
In order to create an instance (object) of this class, we can simply do the following:
abder = Person()
This means that we have created a new object
abder of type
Person. Notice that creating an object is simply having the class name followed by parentheses.
We can identify which type
abder is, and where it belongs in memory by typing:
print abder. In this case, you will get something like the following:
<__main__.Person instance at 0x109a1cb48>
Attributes are like properties we want to add to the class (type). For instance, for our class Person, let's add two attributes:
school, as follows:
class Person: name = '' school = ''
Now, we can create a new object of type Person (instance of Person) with more details, since it now has some attributes, as follows:
abder = Person() abder.name = 'Abder' abder.school = 'ABC University'
Methods are like functions in Python, in that they are defined with the keyword
def and have the same formatting as functions. In our class, let's define a method that prints the person's name and school. The class will look as follows:
class Person: name = '' school = '' def print_name(self): print self.name def print_school(self): print self.school abder = Person() abder.name = 'Abder' abder.school = 'XY University' abder.print_name() abder.print_school()
I mentioned above that methods are like functions. But the main difference is that methods need to have an argument conveniently named
self, which refers to the object the method is being called on (i.e. abder). Notice that in calling the method we don't need to pass
self as an argument, as Python will handle that for us.
If we don't put
self as an argument in
print_name(), here is how Python will complain:
Traceback (most recent call last): File "test.py", line 14, in <module> abder.print_name() TypeError: print_name() takes no arguments (1 given)
You can of course pass more than one argument to the method. Let's make the process of printing the
school in one method, as follows:
class Person: name = '' school = '' def print_information(self, name, school): print self.name print self.school abder = Person() abder.name = 'Abder' abder.school = 'XY University' abder.print_information(abder.name, abder.school)
Try and run the program—did you get the same output as before?
In the previous section, we initialized
school by giving them an empty value
' '. But there is a more elegant way of initializing variables to default values, and here is where initialization comes in handy.
The initializer is a special method with the name
__init__ (the method is considered special and will be treated in a special case, and that is why there are double underscores at the beginning and at the end).
Let's modify the previous program to use the initializer. In this case, the program will look as follows:
class Person: def __init__(self, n, s): self.name = n self.school = s def print_name(self): print self.name def print_school(self): print self.school abder = Person('Abder', 'XY University') abder.print_name() abder.print_school()
Notice that the initializer here needs to have two arguments. For instance, if we don't include the
n argument in the initializer, we will get the following error:
Traceback (most recent call last): File "test.py", line 12, in <module> abder = Person('Abder', 'XY University') TypeError: __init__() takes exactly 2 arguments (3 given)
So the bottom line is that with classes you will be able to create your own data types, and with objects you will be able to create instances of those data types. Classes are also composed of attributes (properties) and methods that are actions we perform on those attributes.
What was that data type you always wanted to create? Go ahead and do it!
Source: Tuts Plus