Login
📚 Introduction to Python Programming
Chapters ▾
⇩ Download ▾

11.2 Classes and instances

Learning objectives

By the end of this section you should be able to

  • Create a class with instance attributes, class attributes, and the __init__ method.
  • Use a class definition to create class instances to represent objects.

Classes and instances

In the previous section, a real-world entity, like a person's social media profile, was modeled as a single object. How could a programmer develop a software system that manages millions of profiles? A blueprint that defines the fields and procedures of a profile would be crucial.

In a Python program, a class defines a type of object with attributes (fields) and methods (procedures). A class is a blueprint for creating objects. Individual objects created of the class type are called instances.

Creating instances with __init__

___init___ is a special method that is called every time a new instance of a class is created. self refers to the instance of a class and is used in class methods to access the specific instance that called the method. __init__ uses self to define and initialize the instance's attributes.

Instance attributes vs. class attributes

The attributes shown so far have been instance attributes. An instance attribute is a variable that is unique to each instance of a class and is accessed using the format instance_name.attribute_name. Another type of attribute, a class attribute, belongs to the class and is shared by all class instances. Class attributes are accessed using the format class_name.attribute_name.