DEV Community

Cover image for Working with Python classes and objects
pavanbaddi
pavanbaddi

Posted on • Updated on • Originally published at thecodelearners.com

Working with Python classes and objects

Python is a dynamically typed programming language and also is it is "Functional Programming" and "Object-Oriented Programming".

What is Functional Programming?

In Functional Programming, we defined a function with the required parameters and make a call to function whenever it is required. Example: Suppose we want to get a list of students with marks and display them

def get_students():
    students = [
        {
        'fname' : 'Omkar',
        'lname' : 'J',
        'marks' : [
            {
            'subject_name' : 'Maths',
            'marks_secured' : '70',
            },
            {
            'subject_name' : 'Science',
            'marks_secured' : '60',
            },
        ],
        },
        {
        'fname' : 'Rakesh',
        'lname' : 'K',
        'marks' : [
            {
            'subject_name' : 'Maths',
            'marks_secured' : '56',
            },
            {
            'subject_name' : 'Science',
            'marks_secured' : '47',
            },
        ],
        },
    ]

    return students

def show_students_marks():
    students_list = get_students()

    for i in students_list:
        print("nMarks secured by {} {} in exam".format(i['fname'],i['lname']))
        if len(i['marks']) > 0:
        print(" Subject Name -|- Marks Scored")
        for j in i['marks']:
            print(" {} -|- {} ".format(j['subject_name'],j['marks_secured']))


show_students_marks()

#PYTHON OUTPUT
Marks secured by Omkar J in exam
Subject Name -|- Marks Scored
Maths -|- 70
Science -|- 60

Marks secured by Rakesh K in exam
Subject Name -|- Marks Scored
Maths -|- 56
Science -|- 47

This is a small example in the vast paradigm/patterns of functional programming.

What is Class in Programming?

Classes can be defined as a blueprint/representation of a particular code which deals with the specific context.

What Is Object-Oriented Programming?

Objects are a representation of a class or objects represent a particular class. The above same example will be executed but with Object-Oriented Method.

class Student():

    def get_students(self):
        students = [
            {
            'fname' : 'Omkar',
            'lname' : 'J',
            'marks' : [
                {
                'subject_name' : 'Maths',
                'marks_secured' : '70',
                },
                {
                'subject_name' : 'Science',
                'marks_secured' : '60',
                },
            ],
            },
            {
            'fname' : 'Rakesh',
            'lname' : 'K',
            'marks' : [
                {
                'subject_name' : 'Maths',
                'marks_secured' : '56',
                },
                {
                'subject_name' : 'Science',
                'marks_secured' : '47',
                },
            ],
            },
        ]

        return students

    def show_students_marks(self):
        students_list = self.get_students()

        for i in students_list:
        print("nMarks secured by {} {} in exam".format(i['fname'],i['lname']))
        if len(i['marks']) > 0:
            print(" Subject Name -|- Marks Scored")
            for j in i['marks']:
            print(" {} -|- {} ".format(j['subject_name'],j['marks_secured']))

student_obj = Student()

student_obj.show_students_marks()

#PYTHON OUTPUT
Marks secured by Omkar J in exam
Subject Name -|- Marks Scored
Maths -|- 70
Science -|- 60

Marks secured by Rakesh K in exam
Subject Name -|- Marks Scored
Maths -|- 56
Science -|- 47

Creating a class in Python

To create a class in python use class keyword followed by Class Name.

class Person:

    def show_name():
        print("name")

Creating Object in Python

person1 = Person()
person2 = Person()

Adding Properties to class and creating Objects of class

Properties are just variable which has a class level or function-level scope.

Example
class Person:
    name = "Suzan"

    def show_name():
        print("My name is {}".format(self.name))

In this example, the class property is name which can be accessed inside method using self.name.

Variables with class-level scope

class TestClass:
    age=10 # Variable with class level scope i.e its value can be accessed inside any function(Method()) in the class

    def get_age(self):
        print('age : {}'.format(self.age))


c=TestClass() #Class object named `c` created

c.get_age() # Accessing method `get_age()` from object using dot(.) operator

#PYTHON OUTPUT
age : 10

In the above example, we have created a class named TestClass specified with the property age. You can notice that in get_age(self) we are calling age property using self keyword. The self keyword in python refers to the class itself i.e in this case self is nothing but class TestClass and we are using it are paramter[argument] to the function inside the class and there is no need to call self keyword while calling class function using objects. __init__() a method in python is a special function which is invoked when a new class is created. We can use this special method to set the value of properties inside the class.

class NewClass:
    users_list=[]

    def __init__(self, name, age):
        self.name=name
        self.age=age
        user = {
        'name' : self.name,
        'age' : self.age,
        }
        self.users_list.append(user)

    def show_details(self):
        return self.users_list

a=NewClass('Rake', 15)
a=NewClass('Jonny', 18)
a=NewClass('Sam', 21)
print(a.show_details())

#PYTHON OUTPUT
[{'name': 'Rake', 'age': 15}, {'name': 'Jonny', 'age': 18}, {'name': 'Sam', 'age': 21}]

Accessing properties of Object

Consider the above example the users_list is the property in the Object. To accessing it simple call object_name.property

print(a.users_list)

#PYTHON OUTPUT
[{'name': 'Rake', 'age': 15}, {'name': 'Jonny', 'age': 18}, {'name': 'Sam', 'age': 21}]

Modify properties of Object

a.users_list.append({"name" : "Arnold", "age" : 25})
print(a.users_list)

#PYTHON OUTPUT
[{'name': 'Rake', 'age': 15}, {'name': 'Jonny', 'age': 18}, {'name': 'Sam', 'age': 21}, {'name': 'Arnold', 'age': 25}]

Removing Properties from Objects

Use del keyword to delete properties of objects

del a.users_list

You can go through this article for complete guide to python classes and objects

Reference Posts

Top comments (1)

Collapse
 
iceorfiresite profile image
Ice or Fire

Nice information but please use f-strings!