Skip to content
PythonObject-Oriented Programmingbeginner30 min read

Classes and Instances

Learn how classes define objects, how __init__() initializes instances, and how self and instance attributes work.

In this lesson, you will learn

  • ✓Explain what a class, object, and instance are and how they relate.
  • ✓Define a class using the class keyword and create instances from it.
  • ✓Understand the purpose of __init__() and the self parameter.
  • ✓Create, access, and modify instance attributes.
  • ✓Explain why separate instances can store different attribute values.
  • ✓Distinguish instance attributes from class attributes at a basic level.
  • ✓Trace object creation and identify common attribute-related errors.

1. What are classes, objects, and instances?

A class is a definition for a type of object. It can describe the data an object stores and the operations it supports.

An object is an individual value that exists while a Python program runs. An instance is an object created from a particular class.

Think of a class as a blueprint and an instance as one individual item built from that blueprint. The blueprint describes what an item can contain, but each item can have its own values.

For example, a Student class can represent students. One instance can represent a student named Asha, while another can represent a student named Ravi. Both are instances of the same class, but they can store different names.

Python already provides many classes, including str, int, list, and dict. You can also define classes for concepts in your own programs.

Create your first class and instance

Create your first class and instance
python
class Dog:
pass
 
dog = Dog()
print(type(dog).__name__)
print(isinstance(dog, Dog))
Output
Dog True

class Dog: defines a new class named Dog. pass is a placeholder statement. It allows the class body to be empty for now. Dog() creates an instance of the Dog class. The variable dog refers to that instance. type(dog).__name__ displays the class name, Dog. isinstance(dog, Dog) returns True because dog is an instance of Dog.

Note

A class defines a type. Calling that class creates an instance. Two instances of the same class are not automatically the same object.

2. Defining a class with attributes

Attributes are names associated with an object. They allow an object to store information, such as a dog's name, a book's title, or a student's age.

You can access an attribute using dot notation: object.attribute. For example, dog.name accesses the name attribute of the object referenced by dog.

For instance-specific data, a common approach is to initialize attributes inside __init__(). This method is called automatically as part of normal instance creation.

The attribute assignment self.name = name creates or updates the name attribute on the particular instance represented by self. The right-hand name is a parameter; the left-hand self.name is an object attribute.

Store a name in an instance

Store a name in an instance
python
class Dog:
def __init__(self, name):
self.name = name
 
dog = Dog("Milo")
print(dog.name)
Output
Milo

The class defines a method named __init__(). The parameter name receives the argument "Milo". self refers to the instance being initialized. self.name = name stores the supplied string in that instance's name attribute. dog.name retrieves the stored value, so Python prints Milo.

Note

Dot notation is used to access attributes. The attribute name after self. is the name stored on the instance; the parameter on the right supplies its value.

3. Understanding __init__()

__init__() is a special method that initializes a newly created instance. It is commonly called the initializer.

When you write Dog("Milo"), Python creates a Dog instance and invokes its initialization logic with the supplied argument. You normally do not call __init__() directly.

The first parameter of an instance initializer is conventionally named self. Other parameters receive the values supplied when the class is called.

The initializer can assign multiple attributes, perform basic validation, or set up an object's initial state.

A common beginner misunderstanding is to think that __init__() creates the object by itself. More precisely, instance creation and initialization are separate steps: Python creates the instance, then __init__() initializes it.

Trace the initialization process

Trace the initialization process
python
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
 
student = Student("Asha", 21)
print(student.name)
print(student.age)
Output
Asha 21

Python evaluates Student("Asha", 21). A new Student instance is created. __init__() receives the instance as self, "Asha" as name, and 21 as age. The initializer assigns self.name and self.age. The variable student refers to the initialized instance. The print statements display the two stored attribute values.

Caution

__init__() should normally initialize an instance and implicitly return None. Do not return another value from __init__(); Python raises a TypeError if its return value is not None.

4. What is self?

self is the conventional name for the first parameter of an instance method. It refers to the particular instance on which the method is being called.

Python supplies the instance automatically when you call an instance method through an object. You normally write object.method(argument), not object.method(object, argument).

The name self is a strong Python convention, not a reserved keyword. Although a different parameter name is technically possible, using self makes code consistent and easier to understand.

Consider two Student instances. When the initializer runs for the first student, self refers to that first instance. When it runs for the second student, self refers to the second instance. That is why the same assignment statement can initialize different objects independently.

self refers to the current instance

self refers to the current instance
python
class Student:
def __init__(self, name):
self.name = name
 
student_a = Student("Asha")
student_b = Student("Ravi")
 
print(student_a.name)
print(student_b.name)
Output
Asha Ravi

During Student("Asha"), self refers to the instance stored in student_a. During Student("Ravi"), self refers to the separate instance stored in student_b. Both instances use the same initializer code. The values differ because each initializer call receives a different name.

Note

Read self.name = name as: store the value in the name attribute of the current instance. The name parameter and the self.name attribute are different things.

5. Reading and modifying instance attributes

After an instance has been created, you can read its attributes using dot notation. For example, book.title reads the title attribute.

You can also assign a new value to an attribute using object.attribute = value. This changes the attribute on that particular object.

In ordinary Python classes, instances can generally have new attributes assigned dynamically. If you accidentally use the wrong attribute name, Python may create a different attribute instead of changing the one you intended.

Attribute names are case-sensitive. title and Title are different names.

Change an attribute after creating an object

Change an attribute after creating an object
python
class Book:
def __init__(self, title):
self.title = title
 
book = Book("Dune")
print(book.title)
 
book.title = "Foundation"
print(book.title)
Output
Dune Foundation

The instance is initialized with the title Dune. The first print displays the current title. The assignment updates the same instance's title attribute. The second print displays the new value, Foundation.

Caution

Python does not automatically know that nam is a typo for name. Check attribute spelling carefully, because a misspelled assignment can create a new attribute rather than updating the intended one.

6. Instance attributes versus class attributes

An instance attribute belongs to a particular instance. It is commonly assigned through self inside __init__(). Different instances can hold different values for the same instance attribute name.

A class attribute is defined in the class body, outside the instance methods. It belongs to the class and can be accessed through the class itself or through instances when an instance attribute with the same name does not override it.

Class attributes are useful for values shared across instances, such as a common category or a constant. Instance attributes are useful for values that vary from object to object, such as a student's name.

Attribute lookup checks the instance before falling back to the class for ordinary attributes. Assigning to an instance attribute with the same name as a class attribute generally creates or updates the instance-level value; it does not change the class attribute.

A shared class attribute and separate instance attributes

A shared class attribute and separate instance attributes
python
class Student:
school = "Central School"
 
def __init__(self, name):
self.name = name
 
first = Student("Asha")
second = Student("Ravi")
 
print(first.school)
print(second.school)
print(first.name, second.name)
Output
Central School Central School Asha Ravi

school is defined in the class body, so it is a class attribute. Neither instance has its own school attribute, so both lookups find the class attribute. name is assigned through self in __init__(), so each instance stores its own name. Both students share the school value while retaining different names.

Note

For this lesson, remember the basic distinction: instance attributes hold per-object state, while class attributes are defined on the class and can be shared through attribute lookup. Mutable class attributes have additional pitfalls that should be studied separately.

7. Comparing instances and checking identity

Every instance is an individual object. Two instances can have identical attribute values and still be different objects.

The is operator tests object identity: whether two references point to the exact same object. It does not compare whether two objects contain equal data.

The == operator checks equality according to the object's equality behavior. For a simple user-defined class that does not implement custom equality, two separate instances usually compare unequal by default, even if their attributes match.

Use is when identity is what matters, especially when checking whether a value is None. Use == when you want to compare values.

Two instances with the same data

Two instances with the same data
python
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
 
first = Point(2, 3)
second = Point(2, 3)
third = first
 
print(first is second)
print(first is third)
print(first.x == second.x and first.y == second.y)
Output
False True True

first and second were created by separate calls to Point(), so they are different objects. third = first creates another reference to the same object as first. The final expression compares the coordinates, not the identity of the Point objects. The objects can contain the same coordinate values even though they are distinct instances.

Note

Identity and equality answer different questions. Two objects can contain the same data without being the same object.

8. Common errors and edge cases

Classes introduce a few errors that are especially useful to recognize early. These often involve missing constructor arguments, incorrect attribute names, or confusing the class with an instance.

Trace the constructor call and compare its supplied arguments with the parameters declared by __init__(). Then check which attributes were initialized and which object you are accessing.

An instance attribute usually exists only after your code assigns it. If you try to read an attribute that does not exist on the instance or its class, Python raises AttributeError.

Accessing an attribute that does not exist

Accessing an attribute that does not exist
python
class Dog:
def __init__(self, name):
self.name = name
 
dog = Dog("Milo")
print(dog.name)
# print(dog.age) # Uncommenting this raises AttributeError.
Output
Milo

The initializer creates the name attribute, so dog.name is valid. No age attribute is defined on this instance or its class in the example. If the commented statement is uncommented, Python raises AttributeError. The example leaves the invalid statement commented out so the shown program runs successfully.

Caution

A class definition can be syntactically valid while the program still fails at runtime because a required argument is missing or an attribute has not been initialized.

9. Putting the concepts together

A class becomes useful when it groups related information into a meaningful object. For example, a Book object can store a title, author, and page count together.

When designing a class, identify which values belong to each individual object, initialize those values consistently, and use descriptive attribute names.

Keep this lesson focused on object creation and attributes. In the next lesson, you will build on these ideas by defining instance methods that operate on an object and use self to access its state.

A small Book class

A small Book class
python
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
 
book_one = Book("Dune", "Frank Herbert", 412)
book_two = Book("The Hobbit", "J. R. R. Tolkien", 310)
 
print(book_one.title, "by", book_one.author)
print(book_two.title, "by", book_two.author)
print(book_one.pages + book_two.pages)
Output
Dune by Frank Herbert The Hobbit by J. R. R. Tolkien 722

Book defines the attributes that each instance will initialize. book_one and book_two are separate Book instances. Each instance stores its own title, author, and pages. The first two print statements access attributes on different instances. The last statement adds the two page counts: 412 + 310 = 722.

Note

A useful class models one kind of thing. Each instance represents one individual thing and stores its own state through its instance attributes.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Thinking that a class and an instance are the same thing.

Why it happens: A class defines a type and its behavior, while an instance is a particular object created from that class.

Incorrect Approach
script.py
python
Thinking that a class and an instance are the same thing.
Correct Solution
script.py
python
A class defines a type; calling the class creates an individual instance of that type.

Key takeaway: A class defines a type; calling the class creates an individual instance of that type.

#2 Forgetting self in an instance method definition.

Why it happens: Instance methods receive the instance as their first argument by convention, usually named self, so it must appear in the method definition.

Incorrect Approach
script.py
python
Forgetting self in an instance method definition.
Correct Solution
script.py
python
Include self as the first parameter of ordinary instance methods, including __init__(). Python supplies the instance when the method is called through an object.

Key takeaway: Include self as the first parameter of ordinary instance methods, including __init__(). Python supplies the instance when the method is called through an object.

#3 Confusing name with self.name.

Why it happens: A bare local name is separate from an instance attribute; use self.name to read or update the attribute stored on the object.

Incorrect Approach
script.py
python
Confusing name with self.name.
Correct Solution
script.py
python
name is a local parameter in the initializer, while self.name is an attribute stored on the current instance.

Key takeaway: name is a local parameter in the initializer, while self.name is an attribute stored on the current instance.

#4 Assuming all instances share their instance attributes.

Why it happens: Instance attributes are stored separately on each object unless the code deliberately shares a mutable class attribute.

Incorrect Approach
script.py
python
Assuming all instances share their instance attributes.
Correct Solution
script.py
python
Each instance has its own instance-level state. Assigning self.name during initialization stores the value on the current instance.

Key takeaway: Each instance has its own instance-level state. Assigning self.name during initialization stores the value on the current instance.

#5 Assuming a missing attribute automatically evaluates to None.

Why it happens: Accessing an attribute that does not exist normally raises AttributeError; Python does not silently return None.

Incorrect Approach
script.py
python
Assuming a missing attribute automatically evaluates to None.
Correct Solution
script.py
python
Accessing an attribute that does not exist normally raises AttributeError. Define the attribute or check for its existence when appropriate.

Key takeaway: Accessing an attribute that does not exist normally raises AttributeError. Define the attribute or check for its existence when appropriate.

#6 Using a class attribute for data that should belong to each instance.

Why it happens: Class attributes are shared through the class unless shadowed, so per-object state should normally be stored on each instance.

Incorrect Approach
script.py
python
Using a class attribute for data that should belong to each instance.
Correct Solution
script.py
python
Use instance attributes for per-object data. A mutable class attribute can accidentally be shared by all instances that access it.

Key takeaway: Use instance attributes for per-object data. A mutable class attribute can accidentally be shared by all instances that access it.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is the difference between a class and an instance?
Answer:
A class defines a type of object and describes its possible attributes and behavior. An instance is an individual object created from that class. Multiple instances can share the same class while storing different instance attribute values.
Q2:What is __init__() in Python?
Answer:
__init__() is a special initialization method called during normal instance creation. It commonly assigns initial attributes such as self.name or self.age. It is not the method that independently creates the object, and it should not return a non-None value.
Q3:What is self in a Python class?
Answer:
self conventionally names the first parameter of an instance method and refers to the instance on which that method is operating. Python supplies the instance automatically when the method is called through an object.
Q4:Why do two instances of the same class have different attribute values?
Answer:
Each instance has its own instance-level state. When __init__() assigns self.name or self.size, the assignment targets the particular instance being initialized. Separate constructor calls can therefore store different values.
Q5:What is the difference between an instance attribute and a class attribute?
Answer:
An instance attribute belongs to an individual object and commonly stores per-object state. A class attribute is defined in the class body and can be accessed through the class or through instances using normal attribute lookup. Assigning the same attribute name on an instance normally creates an instance-level value that takes precedence for that instance.
Q6:What is the difference between is and ==?
Answer:
is checks whether two references point to the same object. == checks equality according to the objects' equality behavior. Two separate objects can contain the same values without being identical.
Q7:What happens if you access an attribute that was never initialized?
Answer:
If attribute lookup cannot find the attribute on the instance or its class, Python normally raises AttributeError. A developer should initialize required attributes consistently and check names carefully.
Q8:Why is self.name = name commonly used inside __init__()?
Answer:
The right-hand name refers to a parameter containing the supplied value. The left-hand self.name stores that value as an attribute on the current instance, allowing the object to retain and expose it after initialization.

Key takeaways

  • A class defines a type, and an instance is an individual object created from that class.
  • Calling a class normally creates a new instance.
  • __init__() initializes an instance and commonly assigns its initial attributes.
  • self conventionally refers to the current instance inside an instance method.
  • self.name = name stores the value of a parameter in the instance's name attribute.
  • Separate instances can store different values for the same instance attribute.
  • Instance attributes and class attributes have different roles and attribute lookup behavior.
  • The is operator checks identity, while == checks equality.
  • Accessing an attribute that cannot be found normally raises AttributeError.
  • Use descriptive class and attribute names, and initialize required state consistently.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: