Classes and Objects in Python 3 | OOP's

Author: neptune | 27th-Jan-2023
#Python

We will see the OOPs implementation in Python along with examples.

Introduction to OOP’s

Object-oriented programming can model real-life scenarios and suit the development of large and complex applications.


What is an Object?

In real life, an object is something that you can sense and feel. For example Car, Bicycles, Mango, and more.

However, in Software development, an object is a non-tangible entity, which holds some data and is capable of doing certain things.


What is Class?

A Class is a template that contains:

1. instructions to build an object.

2. methods that can be used by the object to exhibit a specific behaviour.

“class” keyword is used to define a class in Python.

Syntax

class <ClassName>(<parent1>, ... ):

    class_body


Example:

class Person:

    pass

Above example defines Person class without anybody.


How to create Objects?

An object is created by calling the class name followed by a pair of parenthesis.

class Person:             

    pass                    

p1 = Person()      # Creating the object 'p1'

>>>print(p1)

The output of print on object p1, tell you what class it belongs to and hints at the memory address it is referenced to.


Setting Attributes

  • You can set attributes, one at a time, to an instantiated object and access it using the dot notation.

  • The value which is set to an attribute can be anything: a Python primitive, a built-in data type, or another object. It can even be a function or a class.

Example

class Person:

    pass

p1 = Person()

p1.fname = 'Jack'

p1.lname = 'Simmons'

>>>print(p1.fname, '-', p1.lname)  # -> 'Jack - Simmons'


1. You can also set multiple attributes, at once, by defining the initializer method, __init__, inside the class.

2. This method is called by default, during an object creation.

3. It takes values passed inside the parenthesis, during an object creation, as it's arguments.

4. It also takes self as the first argument, which refers to the current object.

5. In the following example, the Person class sets two attributes using __init__ method.

class Person:

    def __init__(self, fname, lname):

        self.fname = fname

        self.lname = lname

p1 = Person('George', 'Smith')   

print(p1.fname, '-', p1.lname)           # -> 'George - Smith'

Each class or a method definition can have an optional first line, known as docstring.


Example:

class Person:

    'Represents a person.'

    def __init__(self, fname, lname):

        'Initialises two attributes of a person.'

        self.fname = fname

        self.lname = lname

Once documented, you can load the script into an interactive interpreter and run the help command on the Person class.


>>>help(Person)


Help on class Person in module __main__:


class Person(builtins.object)

 |  Represents a person.

 |  

 |  Methods defined here:

 |  

 |  __init__(self, fname, lname)

 |      Initialises two attributes of a person.


If you have questions, or simply would like to share your thoughts, then feel free to reach out in the comments section below.




Related Blogs
How to extract Speech from Video using Python?
Author: neptune | 16th-Jun-2023
#Python #Projects
Simple and easy way to convert video into audio then text using Google Speech Recognition API...

How to download video from youtube using python module ?
Author: neptune | 15th-Jun-2023
#Python
We will let you know how you can easily download the Youtube high quality videos along with subtitle, thumbnail, description using python package..

Deploy Django project on AWS with Apache2 and mod_wsgi module.
Author: neptune | 18th-May-2024
#Python #Django
In this blog I use the AWS Ubuntu 18.22 instance as Hosting platform and used Apache2 server with mod_wsgi for configurations. We create a django sample project then configure server...

Best Python package manager and package for virtual environment ?
Author: neptune | 18th-Jun-2023
#Python #Pip
We will explore the options of Pip, Virtualenv, Anaconda, and also introduce Pyenv as a helpful tool...

Core Python Syllabus for Interviews
Author: neptune | 26th-Jul-2023
#Python #Interview
STRING MANIPULATION : Introduction to Python String, Accessing Individual Elements, String Operators, String Slices, String Functions and Methods...

Mostly asked Python Interview Questions - 2023.
Author: neptune | 30th-May-2023
#Python #Interview
Python interview questions for freshers. These questions asked in 2022 Python interviews...

Python Built-in functions lambda, map, filter, reduce.
Author: neptune | 15th-Jun-2023
#Python
We are going to explore in deep some important Python build-in functions lambda, map, filter and reduce with examples...

How to reverse string in Python ?
Author: neptune | 16th-May-2022
#Python
We are going to explore different ways to reverse string in Python...

Python 3.9 new amazing features ?
Author: neptune | 26th-Jul-2023
#Python
Python 3.9 introduces new features such as dictionary union, string methods to remove prefixes and suffixes, type hinting, and speed improvements for built-in functions...

10 Proven Ways to Earn Money Through Python
Author: neptune | 11th-Apr-2023
#Python
Python offers numerous earning opportunities from web development to teaching, data analysis, machine learning, automation, web scraping, and more...

5 Languages that Replace Python with Proof
Author: neptune | 13th-Apr-2023
#Python
Julia, Rust, Go, Kotlin, and TypeScript are modern languages that could replace Python for specific use cases...

Monkey Patching in Python: A Powerful Yet Controversial Technique
Author: neptune | 01st-Aug-2023
#Python
Monkey patching in Python is a dynamic technique to modify code at runtime. It can add/alter behavior, but use it judiciously to avoid maintainability issues...

Building a Simple Chatbot with Python and openpyxl
Author: neptune | 25th-Jun-2024
#Python #Projects
This chatbot reads questions and answers from an Excel file and provides responses based on user input...

Best Practices for Managing Requests Library Sessions When Interacting with Multiple APIs ?
Author: neptune | 22nd-Aug-2024
#Python
When working with Python's `requests` library, managing sessions is crucial, especially when your application interacts with multiple APIs...

How to Update XML Files in Python?
Author: neptune | 01st-Jul-2024
#Python
Handling XML files in Python is straightforward with the `xml.etree.ElementTree` module...

How to Ensure Proper Namespace Handling in XML with Python's lxml Library
Author: neptune | 01st-Jul-2024
#Python
By using `lxml`, you can effectively manage XML namespaces and ensure that your XML structure remains intact during updates...

View More