PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Python Object-Oriented Programming (OOP) » Classes and Objects in Python

Classes and Objects in Python

Updated on: December 4, 2026 | 34 Comments

Python is an object-oriented programming language. In Python, you organize data and the code that works on it using classes. A class is a code template for creating objects.

After reading this article, you will learn:

  • Class and objects in Python, and what self means
  • Class attributes and methods
  • Creating and accessing object properties
  • Modify and delete an object, and control how it is printed with __str__() and __repr__()

Table of contents

  • What is a Class and Objects in Python?
  • Create a Class in Python
  • Create Object of a Class
  • What is self in Python?
  • Class Attributes
  • Class Methods
  • Class Naming Convention
  • pass Statement in Class
  • Object Properties
    • Modify Object Properties
    • Delete object properties
  • Delete Objects
  • String representation of an object
  • Useful built-in functions for objects
  • Summary

What is a Class and Objects in Python?

  • Class: The class is a user-defined data structure that binds the data members and methods into a single unit. Class is a blueprint or code template for object creation. Using a class, you can create as many objects as you want.
  • Object: An object is an instance of a class. It is a collection of attributes (variables) and methods. We use the object of a class to perform actions.

Objects have two characteristics: They have states and behaviors (an 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.

In short, every object has the following properties:

  • Identity: Every object must be uniquely identified.
  • State: An object has attributes that represent its state, or its data.
  • Behavior: An object has methods that represent its behavior.

In Python, everything is an object: numbers, strings, lists, functions, and the objects you create from your own classes. An object often models a real-life entity. It bundles data together with the functions that operate on that data.

For example, If we design a class based on the states and behaviors of a Person, its states can be represented as instance variables and its behaviors as methods.

Understand class and object in Python
Understand class and objects in Python

A real-life example of class and objects.

Class: Person

  • State: Name, Sex, Profession
  • Behavior: Working, Study

Using the above class, we can create multiple objects that depict different states and behavior.

Object 1: Jessa

  • State:
    • Name: Jessa
    • Sex: Female
    • Profession: Software Engineer
  • Behavior:
    • Working: She is working as a software developer at ABC Company
    • Study: She studies 2 hours a day

Object 2: Jon

  • State:
    • Name: Jon
    • Sex: Male
    • Profession: Doctor
  • Behavior:
    • Working: He is working as a doctor
    • Study: He studies 5 hours a day

As you can see, Jessa is female, and she works as a Software engineer. On the other hand, Jon is male, and he works as a doctor. Here, both objects are created from the same class, but they have different states and behaviors.

Create a Class in Python

In Python, a class is defined using the class keyword, followed by the class name and a colon. The syntax to create a class is given below.

Syntax

class class_name:
    '''This is a docstring. I have created a new class'''
    <statement 1>
    <statement 2>
    .
    .
    <statement N>Code language: Python (python)
  • class_name: It is the name of the class
  • Docstring: It is the first string inside the class and has a brief description of the class. Although not mandatory, this is highly recommended.
  • statements: Attributes and methods

Example: Define a class in Python

In this example, we are creating a Person Class with name, sex, and profession instance variables.

class Person:
    def __init__(self, name, sex, profession):
        # data members (instance variables)
        self.name = name
        self.sex = sex
        self.profession = profession

    # Behavior (instance methods)
    def show(self):
        print('Name:', self.name, 'Sex:', self.sex, 'Profession:', self.profession)

    # Behavior (instance methods)
    def work(self):
        print(self.name, 'working as a', self.profession)Code language: Python (python)

Create Object of a Class

To use a class, you create objects from it. You create an object by calling the class name like a function. Creating an object is called instantiation, and the object is also called an instance of the class.

A constructor is a special method used to create and initialize an object of a class. This method is defined in the class.

In Python, creating an object happens in two steps: object creation and object initialization.

  • Internally, the __new__ is the method that creates the object
  • Then, the __init__() method initializes it, for example, by setting its instance variables. This is the method you usually write yourself.

Read More: Constructors in Python

Syntax

<object-name> = <class-name>(<arguments>)  Code language: Python (python)

Below is the code to create the object of a Person class

jessa = Person('Jessa', 'Female', 'Software Engineer')Code language: Python (python)

The complete example:

class Person:
    def __init__(self, name, sex, profession):
        # data members (instance variables)
        self.name = name
        self.sex = sex
        self.profession = profession

    # Behavior (instance methods)
    def show(self):
        print('Name:', self.name, 'Sex:', self.sex, 'Profession:', self.profession)

    # Behavior (instance methods)
    def work(self):
        print(self.name, 'working as a', self.profession)

# create object of a class
jessa = Person('Jessa', 'Female', 'Software Engineer')

# call methods
jessa.show()
jessa.work()
Code language: Python (python)

Output:

Name: Jessa Sex: Female Profession: Software Engineer
Jessa working as a Software Engineer

What is self in Python?

Every instance method, including __init__(), takes self as its first parameter. self refers to the object on which the method is called, so self.name means “the name attribute of this particular object”.

You never pass self yourself. When you write jessa.show(), Python automatically calls Person.show(jessa), passing the object as self. The name self is a convention, not a keyword, but you should always use it.

Class Attributes

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

A class can have two kinds of attributes:

  • 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 class, but outside of any instance method or __init__() method.
Class Attributes in Python
Class Attributes in Python

Objects don’t share instance attributes. Every object has its own copy, with values unique to that object.

Class variables, on the other hand, are shared by all instances of the class. Unlike instance variables, their value is the same for every object.

Only one copy of a class variable exists, and it is shared between all objects of the class.

Accessing properties and assigning values

  • An instance attribute can be accessed or modified by using the dot notation: instance_name.attribute_name.
  • A class variable is read with the class name (ClassName.variable) or through an object, but it should be modified using the class name. Assigning through an object creates a new instance variable instead.

Example

class Student:
    # class variables
    school_name = 'ABC School'

    # constructor
    def __init__(self, name, age):
        # instance variables
        self.name = name
        self.age = age

s1 = Student("Harry", 12)
# access instance variables
print('Student:', s1.name, s1.age)

# access class variable
print('School name:', Student.school_name)

# Modify instance variables
s1.name = 'Jessa'
s1.age = 14
print('Student:', s1.name, s1.age)

# Modify class variables
Student.school_name = 'XYZ School'
print('School name:', Student.school_name)Code language: Python (python)

Output

Student: Harry 12
School name: ABC School
Student: Jessa 14
School name: XYZ School

Class Methods

In Object-oriented programming, you can define the following three types of methods inside a class.

  • 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 type of methods we should declare as a class method.
  • Static method: It is a general utility method that performs a task in isolation. It receives neither self nor cls, so it can’t access instance or class variables directly. Define it with the @staticmethod decorator.
Python class method vs static method vs instance method
class method vs static method vs instance method

Instance methods work on the instance level (object level). For example, two objects created from the Student class may have different names, marks, roll numbers, and so on. Using instance methods, we can access and modify the instance variables.

A class method is bound to the class and not to an object. It receives the class as its first argument (cls), so it can access and modify class variables, but not instance variables. Define it with the @classmethod decorator.

Read More: Python Class Method vs. Static Method vs. Instance Method

Example: Define and call an instance method and class method

# class methods demo
class Student:
    # class variable
    school_name = 'ABC School'

    # constructor
    def __init__(self, name, age):
        # instance variables
        self.name = name
        self.age = age

    # instance method
    def show(self):
        # access instance variables and class variables
        print('Student:', self.name, self.age, Student.school_name)

    # instance method
    def change_age(self, new_age):
        # modify instance variable
        self.age = new_age

    # class method
    @classmethod
    def modify_school_name(cls, new_name):
        # modify class variable
        cls.school_name = new_name

s1 = Student("Harry", 12)

# call instance methods
s1.show()
s1.change_age(14)

# call class method
Student.modify_school_name('XYZ School')
# call instance methods
s1.show()
Code language: Python (python)

Output

Student: Harry 12 ABC School
Student: Harry 14 XYZ School

Class Naming Convention

Naming conventions make code easier to read in any programming language. Sensible names save time and effort later, and readable code is one of the guiding principles of Python (see the PEP 8 style guide).

Follow these conventions when naming a class in Python:

  • Rule-1: Class names should follow the UpperCamelCase (also called PascalCase) convention, for example, Person or BankAccount.
  • Rule-2: Exception classes should end in “Error“.
  • Rule-3: If a class is mainly used like a function (it is called directly and behaves like one), it may be named in lowercase, like a function.
  • Rule-4: Python’s built-in classes, such as int, list, and dict, are typically lowercase words.

pass Statement in Class

In Python, the pass is a null statement. Therefore, nothing happens when the pass statement is executed.

Python doesn’t allow empty blocks in loops, function definitions, or class definitions. The pass statement fills such a block without doing anything (it is a “no operation”). It is generally used as a placeholder for code you plan to add later.

For example, suppose you want to define a class now but implement it later. A class can’t have an empty body, so use pass to give it a body that does nothing.

Example

class Demo:
  passCode language: Python (python)

In the above example, we defined class without a body. To avoid errors while executing it, we added the pass statement in the class body.

Object Properties

Every object has properties. An object property is an association between a name and a value.

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

Object Properties
Object Properties

Modify Object Properties

You can set or modify an object’s properties after it is created by assigning to them directly with the dot operator.

object_name.property_name = valueCode language: Python (python)

Example

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 redCode language: Python (python)

Delete object properties

We can delete the object property by using the del keyword. After deleting it, if we try to access it, we will get an error.

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")

# Deleting Object Properties
del obj.name

# Accessing object properties after deleting
print(obj.name)
# Output: AttributeError: 'Fruit' object has no attribute 'name'Code language: Python (python)

The attribute name has been deleted, so trying to access it raises an AttributeError.

Delete Objects

You can also delete an object using the del keyword. This works for any object, such as an object of your own class, a list, a tuple, or a set. Strictly speaking, del deletes the variable name. Python frees the object’s memory once no variable refers to it anymore.

Syntax

del object_nameCode language: Python (python)

Example: Deleting object

class Employee:
    department = "IT"

    def show(self):
        print("Department is ", self.department)

emp = Employee()
emp.show()

# delete object
del emp

# Accessing after delete object
emp.show()
# Output : NameError: name 'emp' is not defined Code language: Python (python)

In the above example, we create the object emp of the class Employee. After that, using the del keyword, we deleted that object.

String representation of an object

If you print an object of your own class, Python shows something like <__main__.Book object at 0x7f...>, which isn’t very useful. Define the special methods __str__() and __repr__() to control how your objects are displayed:

  • __str__() returns a friendly, readable string. It is used by print() and str().
  • __repr__() returns an unambiguous string for developers, ideally one that looks like the code that creates the object. It is used in the interactive shell and when the object is inside a list.
class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

    def __str__(self):
        return f"{self.title} by {self.author}"

    def __repr__(self):
        return f"Book({self.title!r}, {self.author!r})"

b = Book("Python Basics", "Jessa")
print(b)        # uses __str__
print(repr(b))  # uses __repr__
print([b])      # lists use __repr__Code language: Python (python)

Output:

Python Basics by Jessa
Book('Python Basics', 'Jessa')
[Book('Python Basics', 'Jessa')]

Useful built-in functions for objects

  • isinstance(obj, ClassName) checks whether an object was created from a class (or one of its subclasses).
  • type(obj) returns the class of an object.
  • hasattr(), getattr(), and setattr() check, read, and set an attribute by its name as a string.
  • vars(obj) returns a dictionary of the object’s instance attributes.
class Person:
    def __init__(self, name):
        self.name = name

p = Person("Jessa")

# you can add a new attribute to a single object at any time
p.city = "London"

print(isinstance(p, Person))         # True
print(type(p).__name__)              # Person
print(hasattr(p, "age"))             # False
print(getattr(p, "age", "unknown"))  # unknown (default value)
setattr(p, "age", 28)
print(p.age)                         # 28
print(vars(p))                       # {'name': 'Jessa', 'city': 'London', 'age': 28}Code language: Python (python)

Summary

  • A class is a blueprint, and an object is an instance created from it. Create a class with the class keyword and an object by calling the class like a function.
  • The __init__() method initializes a new object, and self refers to the object itself.
  • Instance variables belong to one object. Class variables are shared by all objects of the class.
  • A class can have instance methods, class methods (@classmethod), and static methods (@staticmethod).
  • Use the dot operator to read and modify attributes, and del to delete attributes or objects.
  • Define __str__() and __repr__() to give your objects a readable representation.

Filed Under: Python, Python Object-Oriented Programming (OOP)

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Object-Oriented Programming (OOP)

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes
In: Python Python Object-Oriented Programming (OOP)
TweetF  sharein  shareP  Pin

  Python OOP

  • Python OOP
  • Classes and Objects in Python
  • Constructors in Python
  • Python Destructors
  • Encapsulation in Python
  • Polymorphism in Python
  • Inheritance in Python
  • Python Instance Variables
  • Python Instance Methods
  • Python Class Variables
  • Python Class Method
  • Python Static Method
  • Python Class Method vs. Static Method vs. Instance Method
  • Python OOP exercise

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com