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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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.
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.
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.
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.
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.
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.
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.
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?
Q2:What is __init__() in Python?
Q3:What is self in a Python class?
Q4:Why do two instances of the same class have different attribute values?
Q5:What is the difference between an instance attribute and a class attribute?
Q6:What is the difference between is and ==?
Q7:What happens if you access an attribute that was never initialized?
Q8:Why is self.name = name commonly used inside __init__()?
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.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: