Newby Coder header banner

Python Class and Objects

Python Classes and Objects

What are classes and objects in Python?

Object, in simple terms, is a collection of data and methods who function typically related to that data

Class is like an object constructor, or a "blueprint" for creating objects

An object is also called an instance of a class and the process of creating object from a class is called instantiation

Defining a Class in Python

A class is defined by using the keyword class

The name of the class immediately follows the keyword class followed by a colon as follows:

class MyNewClass:
    '''This is a docstring, typically included to provide info about the class'''
          pass 

The first string is called docstring, which is optional, and has a brief description about the class

A class creates a new local namespace where all its attributes are defined, which may be data or functions

A class allows to access its attributes(which are declared as class attributes) as well as to instantiate new objects of that class

Example

Following is the example of a simple Python class

class Employee:
    '''Base class for employee objects'''
    emp_count = 0
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
        Employee.emp_count +=1

    def display_count():
        print("Total Employees ", Employee.emp_count)

    def to_string(self):
        print("Name: ", self.name, ", Salary: ", self.salary) 

Following example creates two objects, emp1 & emp2, of class Employee and prints employee count

emp1 = Employee("Roger", 9000)
emp2 = Employee("Arthur", 4000)
print(emp1.to_string())
print(emp2.to_string())
print(Employee.display_count())
Name: Roger, Salary: 9000
Name: Arthur, Salary: 4000
Total Employees 2

The self Parameter

The selfparameter is the first argument of any function inside a class, and is a reference to the current instance of the class, used to access variables that belongs to the class

It is conventionally called self, though it does not have to be named self, but it has to be the first parameter of any function in the class:

Example

Example using the words not_exactly_self_though_it_contains_self and abc instead of self:

class Person:

    def __init__(not_exactly_self_though_it_contains_self, name, age):
        not_exactly_self_though_it_contains_self.name = name
        not_exactly_self_though_it_contains_self.age = age

    def printName(abc):
        print("Name: " + abc.name)

p1 = Person("Johnson", 26)
p1.printName() 

Output

Name: Johnson

Constructors in Python

All classes have a function called __init__(), which is always executed when a new object of a class is instantiated

This type of function is also called constructor in Object Oriented Programming (OOP), which is typically used to initialize variables

Attributes of an object can be created on the fly in any function of a class using self parameter

Example

Create a class named Person, use the __init__() function to assign values for name and age:

class Person:

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

p1 = Person("Johnson", 26)
print(p1.name)
print(p1.age) 

Output

Johnson
26

Accessing Attributes

An object's attributes can be accessed using the dot operator (.) with its instance

Class variable can be accessed using class name, for example Employee.emp_count

Attributes of classes and objects can added, removed, or modified

#!/usr/bin/python
class Employee:
    'Base class for employee objects'
    emp_count =0
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
        Employee.emp_count += 1

    def display_count(self):
        print("Total Employee %d" %Employee.emp_count)

    def display_employee(self):
        print("Name : ",self.name,", Salary: ",self.salary)


emp1 = Employee("Roger", 9000)
emp2 = Employee("Arthur", 4000)

# Add an 'age' attribute
emp1.age = 16

# Modify 'name' attribute
emp2.name = Doyle

print("Age: ", emp1.age)
print(emp2.to_string())

Output :

Age: 16
Name: Doyle, Salary: 4000

The following builtin methods deal with attributes:

Method Desc
getattr(obj, name[, default]) to access the attribute of object
hasattr(obj,name) to check if an attribute exists or not
setattr(obj,name,value) to set an attribute. If attribute does not exist, then it would be created
delattr(obj, name) to delete an attribute
hasattr(emp1, 'age')    # Returns true if 'age' attribute exists
getattr(emp1, 'age')    # Returns value of 'age' attribute
setattr(emp1, 'age', 22) # Set attribute 'age' to 22
delattr(empl, 'age')    # Delete attribute 'age' 

Built-In Class Attributes

Every Python class keeps following built-in attributes and they can be accessed using dot operator like any other attribute :

Following shows value of these attributes for class Employee mentioned above -

print("Employee.__doc__:", Employee.__doc__)
print("Employee.__name__:", Employee.__name__)
print("Employee.__module__:", Employee.__module__)
print("Employee.__bases__:", Employee.__bases__)
print("Employee.__dict__:", Employee.__dict__) 

Result :

Employee.__doc__: Base class for employee objects
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'display_count':
<function display_count at 0xb7c84994>, 'emp_count': 2,
'to_string': <function to_string at 0xb7c2451c>,
'__doc__': 'Base class for employee objects',
'__init__': <function __init__ at 0xb7c846bc>} 

Deleting Attributes and Objects

Attributes of an object can be deleted using the del statement

>>> e3 = Employee('Dilly', 130)
>>>del e3.salary
>>> e3.to_string()
Traceback(most recent call last):...
    AttributeError: 'Employee' object has no attribute 'salary'
>>>del Employee.display_count
>>> e3.display_count()
Traceback(most recent call last):...
    AttributeError: 'Employee' object has no attribute 'display_count' 

The object itself can be deleted using the del statement

>>>del e3
>>> e3
Traceback(most recent call last):
...NameError: name 'e3' is not defined 
How deletion works

With e3 = Employee('Dilly', 130), a new instance object is created in memory and the name e3 binds with it

On the command del e3, this binding is removed and the name e3 is deleted from the corresponding namespace

The object however continues to exist in memory and if no other name is bound to it, it is later automatically destroyed

This automatic destruction of unreferenced objects in Python is also called garbage collection

ⓘ More on Python Garbage Collection