bytes

tutorials

python

class python

Classes in Python

Module - 7 OOPs in Python
Classes in Python

Overview

Python is an object-oriented programming language. It allows combining data  and functionality. Essentially everything in Python is an object with attributes  and methods. A class defines an object's structure and behavior.

Introduction

In Python, classes are utilized to characterize new types of objects. Classes allow encapsulating data and the functions that work on that data into a single entity. This way, classes give a way to organize code and simplify it to preserve, reuse, and amplify.

Creating a Class in Python

In Python, creating a class is as simple as writing a function. Function declarations begin with the term def, but class definitions begin with the keyword class . After the keyword class , we have the class identifier (the name of the class we defined), followed by the: (colon) operator. In addition, the variables within the class are referred to as attributes. With the dot(.) operator 📍, the characteristics may be retrieved later in the program.

class ClassName:
  #body of class

Example

class Student:
  pass

It should be noted that the term pass implies an empty class. It is just written to prevent problems in the console while running the preceding code.

Python Class Attributes and Methods

To fully utilize Python classes, we must also add functionality to them. We can do this with attributes and methods. Methods are the functions we define within a class. We need to define specific attributes that will hold functions and data. This will enhance our code's performance. Let's briefly explore these additional features.

Python Class Attributes

class attributes are variables that are shared over all instances of a class. They represent characteristics of the class as a whole and are defined outside of any of the class methods. For illustration, in a student class, a class attribute could be the number of students within the class. This attribute would be shared between all instances of the class and might be accessed by any instance.

class Student:
    num_students = 0  # class attribute
    
    def __init__(self, name, age):
        self.name = name
        self.age = age
        Student.num_students += 1  # access class attribute 

# Create two student objects
student_1 = Student("John", 18)
student_2 = Student("Mary", 19)

# Print the total number of students
print(Student.num_students) # Output: 2

The class attribute in this example is num_students. This attribute is shared between all class instances and increments each time a new instance is created. Each class instance can access this attribute to determine the total number of students in the class.

Python Class Methods

Class methods are functions that are defined and associated with a class. They are used to perform operations on the class's data. Class methods are invoked using the class name and not an instance of the class. They are used to perform tasks related to the class itself, such as creating a new class instance, initializing class properties, and more.

class MyClass:
    @classmethod
    def my_method(cls, arg1, arg2):
        # do something with cls, arg1 and arg2

Example

class Person:
    def __init__(self, name):
        self.name = name
    
    @classmethod
    def create_person(cls, name):
        return cls(name)

# Create a new instance of the Person class
person = Person.create_person('John')
print(person.name) # Output: John

The code defines a class called Person, which has an init() method to initialize the name attribute of an instance. It also includes a class method called create_person(), which takes a name as an argument and returns an instance of the Person class with the given name. The create_person() method is invoked utilizing the class name, Person, and not an instance of the class.

Self keyword

In Python, the self keyword is utilized to allude to the class instance. It is crucial for accessing the attributes and methods of the class. The self keyword is used as the first argument at whatever point a method is called. The self keyword binds the class's attributes to the specific instance calling the method at a given time. In other words, it empowers the class's attributes to be gotten to in a particular instance. With the self keyword, it would be clear which instance of the class the attributes and methods belong to. Overall, the self keyword is crucial for establishing the link between an instance of a class and its corresponding attributes and methods. It allows instances to access and modify their attributes dynamically. The self keyword is an integral part of object-oriented programming in Python and efficiently utilizes classes and instances.

Example:

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

  def print_details(self):
    print("Name:", self.name)
    print("Age:", self.age)

emp1 = Employee("John", 25)
emp1.print_details()

In the code above, the self keyword refers to the class instance. It is used to access the class's attributes (name and age). Inside the print_details() method, the self keyword is used to access the name and age attributes of the instance.

Instance Attributes (_init_method) in Python:

Instance attributes are variables owned by the specific instances of a class. They are defined inside the init method of a class and available to each class instance. They are different from class attributes, which the class owns. Instance attributes are used to store information that is unique to each instance.

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

p1 = Person("John", 36)
p2 = Person("Sarah", 28)

print(p1.name) # John
print(p1.age) # 36
print(p2.name) # Sarah
print(p2.age) # 28

In this example, we have defined a Person class with two instance attributes, name, and age. The init method of the Person class takes two parameters (name and age) and sets them as instance attributes on the instance object. We then create two instances of the Person class, p1 and p2, and set the name and age attributes for each instance. Finally, we print out the name and age attributes for each instance, which results in the output "John", "36", "Sarah", and "28".

Python Class Properties

Class properties are variables that are associated with a specific class . These variables are usually declared within the class definition and can be accessed from any class instance. Class properties can be used to store data related to the class and shared among all instances of a class. The property() function is a built-in function in Python that allows us to create, get, and set properties on a class or object. It takes three arguments: a getter function, a setter function, and a deleter function. The getter function is used to retrieve the value of a property, the setter function is used to set the value of a property, and the deleter function is used to delete the property. This allows us to create custom attributes on a class or object easily and also allows us to define custom behavior when accessing or changing the values of those attributes.

Example:

class MyClass:
 
    def __init__(self, name):
        self.name = name
 
    # Create a property object
    name_property = property(fget=lambda self: self.name)
 
    # Create getter, setter, and deleter methods
    def get_name(self):
        return self.name
 
    def set_name(self, value):
        self.name = value
 
    def del_name(self):
        del self.name
 
    # Set the property object's getter, setter, and deleter methods
    name_property = name_property.setter(set_name)
    name_property = name_property.getter(get_name)
    name_property = name_property.deleter(del_name)
 
# Create an object
obj = MyClass("John")
 
# Print the name
print(obj.name_property)
 
# Set the name
obj.name_property = "Mary"
 
# Print the name
print(obj.name_property

This code makes a class named MyClass that includes a name property. It, at that point, makes a property object named name_property, which is related to the name property. It, at that point, creates getter, setter, and deleter methods for the property, which are utilized to get, set, and delete the value of the name property. At last, it sets the property object's getter, setter, and deleter methods to the already created methods. This permits us to effectively get to and modify the value of the name property from any instance of the class.

Conclusion

Python is an object-oriented programming language where everything is an object with attributes and methods. Classes define an object's structure and behavior, allowing for data and functionality to be combined. Attributes and methods add functionality to classes; the self keyword refers to the class instance. Class attributes are variables shared across all class cases, while class methods are functions associated with a class used to perform operations on the class's data.

Key takeaways

  1. Classes are the building blocks of object-oriented programming in Python
  2. Classes allow you to define objects that can have attributes and methods
  3. All objects in Python are instances of classes
  4. Classes are created by using the class keyword followed by the name of the class ✍️
  5. Classes can have multiple attributes, methods, and inheritance 📚
  6. Instances of a class can be created using the class name and parentheses
  7. Variables within a class are called attributes 🔑
  8. Functions within a class are called methods
  9. Classes can be used to create objects that can be used to model real-world objects
  10. Classes add structure and organization to your code

Quiz

  1. What is the purpose of the init() method in a Python class?
    1. To define class variables 
    2. To initialize the class 
    3. To define class methods  
    4. To delete class objects

Answer: b. To initialize the class

  1. What is the correct syntax for creating a class in Python? 
    1. class MyClass 
    2. class MyClass() 
    3. class MyClass:  
    4. class: MyClass

Answer:c. class MyClass:

  1. What is the output of the following code?
class A:
    def **init**(self):
        self.x = 5
obj = A()
print(obj.x)

a. 5  

b. 10 

c. Error 

d. None

Answer:a. 5

  1. What is the purpose of the self parameter in a Python class?
    1. To access instance attributes  
    2. To define class methods 
    3. To store class variables 
    4. To initialize the class

Answer:a. To access instance attributes

Related Programs
Full Stack Data Science with Placement Guarantee of 5+ LPA
Course
20,000 people are doing this course
Become a job-ready Data Science professional in 30 weeks. Join the largest tech community in India. Pay only after you get a job above 5 LPA.
Related Tutorials

AlmaBetter’s curriculum is the best curriculum available online. AlmaBetter’s program is engaging, comprehensive, and student-centered. If you are honestly interested in Data Science, you cannot ask for a better platform than AlmaBetter.

avatar
Kamya Malhotra
Statistical Analyst
Fast forward your career in tech with AlmaBetter
Vikash SrivastavaCo-founder & CPTO AlmaBetter
Vikas CTO
Related Tutorials to watch
Top Articles toRead
AlmaBetter
Made with heartin Bengaluru, India
  • Location
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2022 AlmaBetter