• Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements
CODE OF GEEKS

We at CODE OF GEEKS, aim at providing best and quality content for our users at no extra cost.

    • Study Materials
      • InfyTQ Archive
      • Infosys Archive
      • TCS Archive
      • Accenture Archive
      • AMCAT Archive
      • Capgemini Archive
      • Cisco Archive
      • CoCubes Archive
      • Cognizant(CTS) Archive
      • Deloitte Archive
      • DXC Archive
      • Goldman Sachs Archive
      • Hexaware Technologies Archive
      • LTI Archive
      • MindTree Archive
      • Virtusa Archive
      • Wipro Archive
    • Interview Preparation
      • C Interview Questions
      • Data Structures Interview Questions
      • DBMS Interview Questions
      • HR Interview Questions
      • Java Interview Questions
      • Operating System Interview Questions
      • Python Interview Questions
      • SQL Query Interview Questions
    • Tutorials
      • Node.js Tutorial
      • Express.js Tutorial
      • Python Tutorial
    • Programming
      • C Programming MCQs
      • C Code Snippets – Output Questions
      • Python Code Snippets – Output Questions
      • Java Code Snippets – Output Questions
    • Aptitude
      • Verbal Ability for Placements
CODE OF GEEKS
CODE OF GEEKS
  • Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements

Classes and Objects in Python with examples

  • December 12, 2022
  • CODE OF GEEKS
  • 0


NEXT TUTORIAL >> self variable in Python

Classes and Objects in Python: We all know that Python is an Object oriented programming language as it works around different classes and objects that too with different behaviors. Each and everything in Python is considered to be an object with its own attributes and methods.

Similarly, we can say that a Python Class is a blueprint for creating objects.

Let’s dig in more deep with a real world example,

1. Consider ‘Animal’ as a class and ‘Animal Species’ (Dog, Cat, Bird) as its attributes.



Creating a Class in Python

We can create a class in Python with the keyword class followed by a classname.

General format for a Python class is given as :

class ClassName:
  attribute 1 
  attribute n 
  def __init__(self):
    statements
  def method1():
    statements
  def method2():
    statements

Above class ‘Animal‘ can be defined as :

class Animal:
  def __init__(self):
    self.dog = 'bark'
    self.cat = 'meow'
    self.bird = 'chirp'
  def display(self): 
    print('Dog {}s'.format(self.dog))
    print('Cat {}s'.format(self.cat))
    print('Bird {}s'.format(self.bird))

Writing a class is not the only step that’s required, it should be used somewhere in the code.

To make that class functional, we should create an instance (object) of that class.

Syntax for creating an instance,

instance_name = Classname() 

So, above code becomes,

class Animal:
  def __init__(self):
    self.dog = 'bark'
    self.cat = 'meow'
    self.bird = 'chirp'

  def display(self): 
    print('Dog {}s'.format(self.dog))
    print('Cat {}s'.format(self.cat))
    print('Bird {}s'.format(self.bird))
    
a = Animal() # creating an instance of a class Animal
print('a.dog: ', a.dog) # printing attribute of a class Animal
print('a.cat: ', a.cat) # printing attribute of a class Animal
print('a.bird: ', a.bird) # printing attribute of a class Animal
a.display() # calling method of a class Animal

O/P

Let’s see what happened in above code

1. We have defined a class Animal – with three variables (instance variables) and one method.

2. We have also used __init__() method to initialize the value for the class.

3. a = Animal() : Here, ‘a’ is an instance name. Once this line is executed, a block of memory is allocated on heap depending upon the class attributes.

4. After memory allocation, the special method ‘__init__(self)‘ is called internally. This method is used to store the initial values into the variables.

5. Finally, allocated memory address of the instance is returned into ‘a’.

We can reference any variables or methods using dot operator as:

a.dog, a.cat, a.bird, a.display()

6. ‘self‘ is a default variable and a reference to the current instance of the class, and is used to access variables that belongs to the class. Use of name ‘self‘ is optional, you can name it as per your wish.



Few Facts about Python Class

1. It is suggested to start a Python Class with an ‘uppercase‘ letter. For example, ‘Animal’, ‘God’, ‘Test’, ‘Main’ are some good looking Python classes.

2. Python Class can contain other nested classes. Nested class is a class defined within a class.

3. Python Class can have two or more __init__() methods, in all such cases, only the last __init__() method is considered.

class Main: 
    def __init__(self):
        print('hey')
    def __init__(self):
        print('hi')
    def __init__(self):
        print('hy')
Main()

O/P

hy

Please note that having more than one __init__() method inside a class is really a bad bad practice.

4. Python Class supports modern’s day programming paradigm – Object Oriented Programming principle.

5. It is possible to define relationships among different classes. It is the concept of Inheritance.

That’s all here.

NEXT TUTORIAL >> self variable in Python





Tags: about classes and objects in pythoncalculator using class and object in pythoncan you have a list of objects in pythonclass and instance attributes in pythonclass and instance methods pythonclass and instance variables pythonclass and object attributes in pythonclass and object concept in pythonclass and object difference in pythonclass and object function in pythonclass and object in python definitionclass and object in python hindiclass and object in python practiceclass and object in python quizclass and object in python syntaxclass and object using pythonclass and object variables in pythonclass instance in dictionary pythonclass object and constructor in pythonclass object in python dictionaryclass object python 2class object python 3 exampleclass object python docstringclass object python pickleclass object python testclass variable and instance variable in python exampleclass with object in pythonclasses and object in pythonclasses and object oriented programming in pythonclasses and object oriented programming in python pptclasses and objects in pythonclasses and objects in python edurekaclasses and objects in python example programsclasses and objects in python examplesclasses and objects in python exercisesclasses and objects in python for beginnersclasses and objects in python geeks for geeksclasses and objects in python geeksforgeeksclasses and objects in python hackerrankclasses and objects in python hackerrank solutionclasses and objects in python in hindiclasses and objects in python javatpointclasses and objects in python mcqclasses and objects in python notesclasses and objects in python pdfclasses and objects in python pptclasses and objects in python programclasses and objects in python programizclasses and objects in python questionsclasses and objects in python videosclasses and objects in python w3schoolsclasses and objects in python with examplesclasses and objects in python youtubeclasses and objects on pythonclasses and objects with pythonclasses methods and objects in pythonclasses of objects in pythonclasses vs objects in pythonclasses with multiple objects in pythonconcept of classes and objects in pythoncreate class objects in loop pythoncreating classes and objects in pythoncreating classes and objects using pythondefine class and object in python with exampledefine classes and objects in pythondescribe the relationship between classes and objects in pythondifference between classes and objects in pythonexample for class and object in pythonexplain about class and object in pythonexplain the concept of classes and objects in pythonfirst class objects in python examplehow class and object created in pythonhow to create class and object in python with examplehow to create classes and objects in pythonhow to declare class and object in pythonhow to use classes and objects in pythoninterview questions on classes and objects in pythonintroduction to classes and objects in pythonlearn classes and objects in pythonmcq on classes and objects in pythonmodules classes and objects in pythonmultiple choice questions on classes and objects in pythonoops classes and objects in pythonppt on classes and objects in pythonprogram for classes and objects in pythonprogram using class and object in pythonprograms on classes and objects in pythonpython class objects in listpython classes and objects example programspython classes and objects examplespython classes and objects exercises geeksforgeekspython classes and objects exercises pdfpython classes and objects for dummiespython classes and objects githubpython classes and objects inheritancepython classes and objects projectpython classes and objects sample programspython classes and objects tutorial pdfpython classes and objects w3schoolspython classes objectspython create list of class objectspython create multiple objects of a classpython objects and classes explainedpython programs using classes and objectsquestions on classes and objects in pythonquiz on classes and objects in pythonrelationship between class and object in pythonstore class objects in list pythonto create simple calculator using classes and objects in pythonwhat are class and object in pythonwhat are classes and objects in pythonwhat are first class objects in pythonwhat is class and object in python with examplewhat is class method and object in pythonwhat is classes and objects in pythonwhat is difference between class and object in pythonwhen to use classes and objects in pythonworking of classes and objects in python
  • Previous The Self Variable in Python Class
  • Next Programming in C Language with its features

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Advertise with us

Table of Content – Python

  1. Introduction to Python ▼
    • Python and its features
    • Key Differences : C vs Python
    • Key Differences : Java vs Python
    • Python Flavors
    • PVM and Memory Management in Python

  2. Python Fundamentals ▼
    • 'Hello World' using Python
    • Comments in Python
    • Variables and Garbage Collection in Python
    • Datatypes in Python
    • Determining the Datatype of Literal | type() method
    • Tokens in Python
    • Keywords in Python
    • Identifiers and Naming Convention in Python
    • Literals in Python

  3. Python Operators ▼
    • Operators in Python
    • Python Mathematical Functions

  4. Python User Inputs ▼
    • Taking Inputs | input() function in Python

  5. Python Control Statements ▼
    • Control Statements in Python
    • if-elif-else Statements in Python
    • Looping in Python
    • while loop in Python
    • while-else loop in Python
    • for loop in Python
    • for-else loop in Python
    • Infinite loops in Python
    • Nested loops in Python
    • break Statement in Python
    • continue Statement in Python
    • pass Statement in Python
    • assert Statement in Python
    • return Statement in Python

  6. Python Functions ▼
    • Introduction to Python Functions
    • Python Functions vs Python Methods
    • Local and Global Variables in Python
    • Formal and Actual Arguments in Python
    • Recursion in Python Functions
    • Lambda Functions in Python
    • Function Decorators in Python
    • Function Generators in Python

  7. Python Strings ▼
    • Strings in Python and Basic Operations
    • String Immutability Explained
    • strip() method in Strings
    • find() method in Strings
    • count() method in Strings
    • replace() method in Strings
    • split() method in Strings
    • Switching Cases in Strings
    • startswith() method in Strings
    • endswith() method in Strings

  8. Python Lists ▼
    • Python Lists Basics
    • index() method in list
    • append() method in list
    • insert() method in list
    • copy() method in list
    • remove() method in list
    • pop() method in list
    • sort() method in list
    • reverse() method in list
    • clear() method in list
    • Nested Lists in Python
    • List Comprehensions in Python

  9. Python Sets ▼
    • Python Sets and Basic Operations
    • Adding Elements in Python Sets
    • Removing Elements in Python Sets
    • Union in Python Sets
    • Intersection in Python Sets

  10. Python Tuples ▼
    • Python Tuple Basics
    • Python Tuples Immutability Explained
    • Python Tuples Methods
    • Python Nested Tuples

  11. Python Dictionary ▼
    • Python Dictionary Basics
    • Python Dictionary Sorting
    • Python Dictionary List to Dictionary Conversion
    • Passing Dictionary to Function

  12. Python Classes and Objects ▼
    • Classes and Objects
    • self variable in Python
    • __init__() method in Python
    • Inner Classes
    • Instance variable and methods
    • Class variable and methods

  13. Python OOPs ▼
    • Inheritance and its types
    • super() method in Python
    • Abstract class| Abstract method in Python

  14. Python Exception Handling ▼
    • Errors in Python and its types
    • Exception Handling in Python
    • Types of Exceptions in Python
    • Custom Exceptions in Python

  15. Python File Handling ▼
    • File Handling in Python
    • with statement in Python

  16. Python DateTime Modules ▼
    • datetime module in Python

  17. Python MultiThreading ▼
    • Multithreading in Python

  18. Python Requests Module ▼
    • Python GET Request
    • Python POST Request
    • Python PUT Request

Python Programs

  1. Fibonacci Series till 'N' Numbers

  2. Sum of Digits of a Number

  3. Checking Prime Number

  4. Checking Armstrong Number

  5. Finding Reverse Number (Traditional)

  6. Finding Reverse Number (Pythonic)

  7. Finding Prime Numbers within Range

  8. Finding Prime Numbers within Range Using SOE

  9. Checking Leap year

  10. Calculating Simple Interest

  11. Generate Random Numbers

  12. Calculate Compound Interest

  13. Area of Circle

  14. ASCII Value of Character
CODE OF GEEKS

Subscribe to Newsletter

CODE OF GEEKS

Learn | Code | Achieve

Reach us

[email protected]
We at CODE OF GEEKS, aim at providing quality content to our users at no cost.
CODE OF GEEKS

Important Pages

About us
Advertise
Privacy Policy
Terms and Conditions
Refund Policy
Contact us

Placements – Study Materials

TCS NQT     Wipro     CapGemini
Accenture     MindTree     CTS
DXC     Hexaware Technologies     AMCAT
CoCubes     Goldman Sachs     Dell
Cisco     Deloitte     Virtusa     LTI     Infosys   

Tutorials

Python
Node.js
Express.js
Golang

Recent Posts

Strings in Go and its basic operations
  • August 11, 2023
Introduction to Functions in Go programming
  • August 11, 2023

Copyright @ CODE OF GEEKS. All Rights Reserved.