Python Classes And Objects

Python classes

A class is considered as a blueprint of objects. We can think of the class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows, etc. Based on these descriptions we build the house. House is the object.

Since many houses can be made from the same description, we can create many objects from a class.

Some points on Python class:

  •   Classes are created by keyword class.
  •   Attributes are the variables that belong to a class.
  •   Attributes are always public and can be accessed using the dot (.) operator. Eg.: My class.Myattribute

Syntax: Class Definition

class ClassName:

# Statement

We use the class keyword to create a class in Python. For example,

class ClassName:

# class definition

Here, we have created a class named ClassName.

Let’s see an example,

class Bike:

name = “”

gear = 0

Class attributes

When we design a class, we use instance variables and class variables.

In Class, attributes can be defined into two parts:

  •   Instance variables: The instance variables are attributes attached to an instance of a class. We define instance variables in the constructor ( the __init__() method of a class).
  •   Class Variables: A class variable is a variable that is declared inside of the class, but outside of any instance method or __init__() method.

Class Methods

In Object-oriented programming, Inside a Class, we can define the following three types of methods.

  •   Instance method: Used to access or modify the object state. If we use instance variables inside a method, such methods are called instance methods.
  •   Class method: Used to access or modify the class state. In method implementation, if we use only class variables, then such types of methods should be declared as a class method.
  •   Static method: It is a general utility method that performs a task in isolation. Inside this method, we don’t use instance or class variables because this static method doesn’t have access to the class attributes.

Advantages of Using Classes in Python

    Classes provide an easy way of keeping the data members and methods together in one place, which helps keep the program more organized.

    Using classes also provides another functionality of this object-oriented programming paradigm, that is, inheritance.

    Classes also help in overriding any standard operator.

    Using classes provides the ability to reuse the code, which makes the program more efficient.

    Grouping related functions and keeping them in one place (inside a class) provides a clear structure to the code, which increases the readability of the program.

Types of Classes in Python

There are various types of classes in Python, some of which are mentioned as follows:

  • Python Abstract Class

An abstract class is a class that contains one or more abstract methods. The term “abstract method” refers to a method that has a declaration but no implementation. When working with a large codebase, it might be difficult to remember all the classes. That is when a Python Abstract Class can be used. Python, unlike most high-level languages, does not have an abstract class by default.

  • Python Concrete Class

Concrete classes have only concrete methods, but abstract classes can have both concrete and abstract methods. The concrete class implements abstract methods, but the abstract base class can also do the same by initiating the methods through ‘super ().’

  • Python Partial Class

One of the Python classes, partial, can help us develop functions that only apply subsets of statements and keywords we pass to it to create new objects as a result. We can utilize the ‘Functools’ module for its implementation.

Python objects

An object is called an instance of a class. A class is like a blueprint while an instance is a copy of the class with actual values. 

For example, suppose Bike is a class then we can create objects like bike1, bike2, etc from the class.

Objects have two characteristics: They have states and behaviors (object has attributes and methods attached to it) Attributes represent its state, and methods represent its behavior. Using its methods, we can modify its state.

An object consists of:

  •   State: It is represented by the attributes of an object. It also reflects the properties of an object.
  •   Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects.
  •   Identity: It gives a unique name to an object and enables one object to interact with other objects.

Syntax: Object Definition

obj = ClassName()

print(obj.atrr)

Let’s see an example,

# create class

class Bike:

name = “”

gear = 0

 # create objects of class

bike1 = Bike()

Here, bike1 is the object of the class. Now, we can use this object to access the class attributes.

Object Properties

Every object has properties with it. In other words, we can say that object property is an association between name and value.

For example, a car is an object, and its properties are car color, sunroof, price, manufacture, model, engine, and so on. Here, color is the name and red is the value. Object properties are nothing but instance variables.

Modify Object Properties

Every object has properties associated with them. We can set or modify the object’s properties after object initialization by calling the property directly using the dot operator.

Obj.PROPERTY = value

class Fruit:

def __init__(self, name, color):

        self.name = name

        self.color = color

def show(self):

        print(“Fruit is”, self.name, “and Color is”, self.color)

# creating object of the class

obj = Fruit(“Apple”, “red”)

# Modifying Object Properties

obj.name = “strawberry”

# calling the instance method using the object obj

obj.show()

# Output Fruit is strawberry and Color is red

Access Class Attributes Using Objects

We use the (.) notation to access the attributes of a class. For example,

# modify the name attribute

bike1.name = “Mountain Bike”

 # access the gear attribute

bike1.gear

Here, we have used bike1.name and bike1.gear to change and access the value of name and gear attribute respectively.

Examples of classes and objects

Creating a simple class

Let’s start with a basic example to understand the concept. We’ll create a Person class with attributes for a person’s name and age:

class Person:

def __init__(self, name, age):

        self.name = name

        self.age = age

def greet(self):

        return f”Hello, my name is {self.name} and I am {self.age} years old.”

 # Creating an object of the Person class

person1 = Person(“Alice”, 30)

# Calling the greet method

print(person1.greet())

In this example, we create a Person class with an __init__ constructor and a greet method. We then create an object, person1, from the class and call the greet method on it.

Inheritance

Inheritance is a fundamental concept in OOP. It allows you to create a new class that’s based on an existing class. Let’s create a Student class that inherits from the Person class:

class Student(Person):

def __init__(self, name, age, student_id):

        super().__init__(name, age)

        self.student_id = student_id

 def study(self, subject):

        return f”{self.name} is studying {subject}.”

# Creating a Student object

student1 = Student(“Bob”, 20, “S12345”)

 # Accessing attributes and methods from the Person class

print(student1.greet())

 # Using the study method from the Student class

print(student1.study(“Mathematics”))

In this example, we define a Student class that inherits the attributes and methods from the Person class. It adds new attributes and methods specific to students.

Conclusion

In conclusion, Python’s classes and objects notions are strong ideas that let you write reusable programmes. You may combine information and capabilities into a single entity that is able to be used to build many objects by establishing a class. Using the dot notation, you may access an object’s methods and properties after it has been created. You can develop more logical, effective, and manageable code by comprehending Python’s classes and objects.

Visited 6 times, 1 visit(s) today