We will now introduce Python class construction along with how to create object instances. The example below defines a class Rectangle
along with various methods useful for operating on rectangles such as area
and perimeter
. Run the following code in Repl.it:
class Rectangle:
def __init__(self,x,y):
self.length=x
self.width=y
def __str__(self):
return 'Length='+str(self.length)+' Width='+str(self.width)
def area(self):
return self.width*self.length
def perimeter(self):
return 2*self.width+2*self.length
def rescale(self,a):
self.width=a*self.width
self.length=a*self.length
def __del__(self):
print("This object no longer exists")
examp1=Rectangle(3,5)
print(type(examp1))
print(examp1)
print(examp1.area())
print(examp1.perimeter())
examp1.rescale(2)
print(examp1)
examp2=Rectangle(2,4)
print(examp2)
print(examp2.area())
print(examp2.perimeter())
examp1=42
del examp2
Some important observations:
- The keyword
class
alerts Python that a new class is being defined.
- The class name is Rectangle and the declaration terminates with a colon (:).
- Generally, as a convention, the class name is capitalized.
- All subsequent code contained within the class definition is indented.
- Method definitions (in a manner similar to functions) commence with the def keyword and terminate with a colon (:).
__init__
, __del__
, and __str__
are Python magic methods.
area
, perimeter
and rescale
are user-defined methods contained within the Rectangle
class.
- The self variable is the object currently being referenced (more on this in a moment).
- In Python,
self
is not a reserved keyword, but it is a very strong convention to use this variable name when referring to an object within a class definition.
examp1
and examp2
are objects instantiated from the class Rectangle
- The attributes for each object are
length
and width
- Each object is initialized with its own set of attribute values
- The syntax of method calls such as
examp1.perimeter()
or examp1.rescale(2)
using the dot notation should be familiar at this point in the course.
You can think of the class definition as a brand new variable type endowed with all the attributes and methods defined within the class. The code following the class definition demonstrates how it can be used.Given the class definition, it is possible to create multiple instances called "objects". Each object has access to the methods defined within the class, but retains its own attribute values. For instance, the commands
examp1=Rectangle(3,5)
examp2=Rectangle(2,4)
will instantiate two objects from the class Rectangle: examp1
and examp2
.Each object can use the class methods to compute the area, the perimeter, or rescale using the length and width provided as the input.
The examp1
and examp2
objects are said to be instances of the class Rectangle
.At the time theRectangle(3,5)
and Rectangle(2,4)
commands execute, the __init__
method is automatically called. When Rectangle(3,5)
executes, the length and width attributes for examp1 are set to the input values and, similarly forexamp2
when Rectangle(2,4)
executes. Therefore, the __init__
method is responsible for initializing the attribute values where self
is the object being referred to at the time of execution (you may see others refer to the __init__
method as a constructor). Hence, it is possible to create multiple instances from the same class. This is the beauty of object-oriented programming: each instance has its own attribute values and can reference methods available within the class definition.
One more important point about methods internal to a class definition must be noted. Bear in mind that self
refers to the object currently being operated upon. When a method is called to operate upon an object, observe that self
is an implicit parameter that is not explicitly passed. For example, in the main code, examp1=Rectangle(3,5)
instantiates an object by automatically calling the __init__
method. Notice that there are two arguments passed in the Rectangle(3,5) statement. On the other hand, inside the class definition, the __init__
method has three input arguments including self which must appear first on the input argument list. As another example, consider the examp1.rescale(2)
command. In this case, the input parameter is the value used to rescale the length and width attribute values internal to the examp1
object. Observe that, internal to the class definition, the rescale method has two input arguments. Again, the self
argument is implicit and appears first while the scale parameter is explicitly set by the method call in the main code. Whenever a method is to be called to operate upon an object, the method definition must have self
as the first input argument. After that, all subsequent input arguments should refer to parameters used within the method.
The __del__
dunder method is referred to as the destructor and is responsible for deleting the object when its use has expired. The subject of destructors is often omitted in introductory courses. However, professional coding demands efficient memory management so that if an object is no longer being used, best practices require its removal from memory. In the above example, redefining examp1
as an integer automatically causes the destructor to run as the object has been overwritten. The del
command can be used to delete a variable; hence, the destructor would run upon deleting examp2
.
The __str__
method enables the print(examp1)
command to make sense. Under normal operating circumstances, Python has no idea how to print objects. If no guidance is given, Python simply outputs a 'handle' that can be used to deduce the object's location in memory. This kind of information would not be useful to a high-level programmer. The __str__
method basically gives guidance on how to apply the print
command.
Magic methods are incredibly useful in this way because they execute in response to some action. The __init__
method runs automatically when an object is instantiated, the __del__
method automatically executes when an object is removed and the __str__
method automatically executes when a desired string operation on an object is referred to.
To conclude, you now have a working knowledge of the following terms: class, object, instantiation, self, constructor, destructor, method, and magic method. In addition, you also know how to define a class and instantiate objects with respect to a class. Practice more examples to become comfortable with object-oriented programming.