Introduction to Python Classes

Learn to write classes in python

Posted by PythonStacks on November 03, 2020

Introduction

Object-oriented programming is one of the most effective approaches to writing software. Python is an Object-oriented programming language, therefore, relies heavily on objects.

In this approach of programming, you write classes that represent real-world things, and you create objects based on these classes.

 

Defining a class in python

A Class is an object constructor for creating objects. They provide a means of bundling data and functionality together.

The python class is made up of attributes (data) and methods (functions). 

Attributes and methods are simply defined as normal variables and functions.

Creating the class involves : 

  • Defining the class name
  • Defining the class attributes

 

A Class definition introduces a little bit of new syntax. In Python, a function definition begins with the def keyword, but a class definition begins with a class keyword.

class ClassName:
    # your atrributes

 

Example of a simple class representing a Person as an Object

class Person:
    name = "John"
    age = 11

 Everything defined in the class is called a class attribute and these class attributes can be functions (methods) or variables.

 

The making of an object from a class is called instantiation, and you work with instances of a class.

Creating a new class creates a new type of object, allowing new instances of that type to be made.

An example of the instantiation of the Person class is :

p = Person()

An instance of the Person class is stored in a variable p. So this creates a new object called p.

We can access the attributes of objects using the object name prefix.

p.name        # John
p.age         # 11

 

Note for this class, all instances you create is going to have the same name and age, which is not ideal.

We will have to improve the class so that every instance of a Person we create will have its own name and age.

 

A little more dive into Classes

Let's take a look at a more complex class representing a Person.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

 

There's a lot to notice, but don't worry. This is the basic structure of almost any class you would be writing.

 

 

The __init__() method

Any function that’s part of a class is a method. Everything known about functions applies to methods as well; 

Methods are a special kind of attribute defined just like a function that collectively describes the behaviors of a class (the actions it can do)

The __init__() method on line 2 is a special method that python runs whenever we create a new instance based on the Person class. Note it has two leading underscores and two ending underscores, it helps python to differentiate special methods from regular functions/methods.


We define the __init__() method to have 3 parameters: self, name, and age.

The self parameter is required in a method definition, and it must come first before the other parameters.

It must be included in the definition because when Python calls this __init__() method later, the method call will automatically pass the self argument.
 

Every method call associated with a class automatically passes self, which is a reference to the instance itself; it gives the individual instance access to the attributes and methods in the class.

 

The two variables defined below the method header each have the prefix self.

self.name = name
self.age = age

Any variable prefixed with self is available to every method in the class, and we’ll also be able to access these variables through any instance created from the class.

 

Creating an instance of the Person class

p1 = Person("Harry", 23)            # first  instance 

p2 = Person("Potter", 32)           # second instance

 

The Person class describes the definitive attributes of a Person; p1 and p2  are instances of the Person class;
Simply said, p1 and p2 are objects of type, Person.

When we make an instance of Person, Python calls the __init__() method from the Person class. We also pass Person() a name and an age as arguments. self is passed automatically, so we don’t need to pass it.

Anytime we want to make an instance from the Person class, we’ll provide values for only the last two parameters, name and age.


Accessing Class Attributes

In the Person class definition, self.name = name takes the value stored in the parameter name and stores it in the variable name,
The same process happens with self.age = age.

Variables that are defined in the __init__()  are called instance attributes. They can be accessed by using the dot notation:

p1.name         # Harry

p1.age          # 23

p2.name         # Potter

p2.age          # 32

To display the output, use the print() function. For example: print(p1.name).

 

 

Writing Custom methods in a class

So far, we have been introduced to only one method, the __init__() method which is a special method.

But we need to be able to add our own methods. Let's do that by creating a new class representing a Rectangle.

Brainstorming:

  • A rectangle object requires a height and a width
  • We should be able to perform an operation on the object to get its Area and Perimeter
  • We should be able to represent our object in a string format.
class Rectangle:
    def __init__(self, width, height):                  # special method
        self.width = width
        self.height = height

    def get_area(self):                                 # custom method
        area = self.width * self.height
        return area

    def get_perimeter(self):                            # custom method
        perimeter = (self.width * 2) + (self.height * 2)
        return perimeter
    
    def __str__(self):                                   # special method
        return "width = " + self.width + " & height: " + self.height

 

You should be getting the pattern here; The methods whose names begin and end with double underscores( __methodname__ ) are special methods in python.

In this case __init__() and __str__() are the special methods.

The __str__() method allows us to specify a string representation of our object (Rectangle). That representation is what is displayed when our object is passed as an argument to the print() function.

r1 = Rectangle(4, 2)

r1.width                        # 4
r1.height                       # 2

# accessing methods
r1.get_area()                   # 8
r1.get_perimeter()              # 12

# calling the __str__() method
print(r1)                       # width = 4 & height: 2

 

Note that if the  __str__() method  wasn't defined in the class, print(r1) will give you something like this:

<__main__.Rectangle object at 0x000002884E517400>

Which isn't human-readable. So it is always a good practice to have a string representation of your class.

 

To display the output for example of r1.get_area(), you should write it as print(r1.get_area()).

 

Examples of Class Definitions

A class representing a Student

class Student:
    def __init__(self, name, subject, score):  # __init__() method
        self.name = name
        self.score = score
        self.subject = subject

    def passed(self):  # regular method
        if self.score >= 80:
            return True
        else:
            return False

    def __str__(self):
        return self.name + ": " + self.subject + " student"

# Creating an instance of the class

stud1 = Student('john', 'science', 87)          # first instance of Student
stud2 = Student("prince", 'biology', 34)        # second instance of Student

# accessing a method

print(stud1.passed())           # True

print(stud2.passed())           # False

print(stud1.subject)            # science

print(stud2.subject)            # biology

print(stud1)                    # john: science student

 

 

A Class representing a Programming Language

class Language:
    def __init__(self):
        self.data_types = []

# Using the class

java = Language()

print(java.data_types)             #  []

java.data_types.append('string')
java.data_types.append('double')

print(java.data_types)              # ['string', 'double']

 

Note, writing of efficient methods in class definitions require a stable understanding of functions. Read Introduction to Functions if you are not familiar with functions in python.

 


Share This Post

Tweet Share Share Share

Subscribe to receive updates!

0 Comments

Leave a comment

* Email would not published