11.2 Classes and instances

3 min readjune 24, 2024

Classes in Python are blueprints for creating objects, encapsulating data and behavior. They define attributes and methods that of the will have, allowing for organized and reusable code in .

Instances are individual objects created from a , each with its own set of attributes. By using classes and instances, programmers can model real-world entities and their interactions, making code more intuitive and easier to maintain.

Classes and Instances

Class definition with constructor

Top images from around the web for Class definition with constructor
Top images from around the web for Class definition with constructor
  • Class serves as a blueprint or template for creating objects (an example of object-oriented programming)
    • Defined using
      class
      keyword followed by class name ( convention)
    • Example class names:
      Person
      ,
      Car
      ,
      BankAccount
  • [__init__()](https://www.fiveableKeyTerm:__init__())
    is a special constructor that initializes attributes
    • Called automatically when a new class instance is created
    • Takes
      [self](https://www.fiveableKeyTerm:self)
      as the first parameter, referring to the instance being created
    • Additional parameters can be defined to accept values for instance attributes
      • Example:
        def __init__(self, name, age)
        to initialize
        name
        and
        age
        attributes
  • Instance attributes are variables specific to each instance of a class
    • Defined within
      __init__()
      using
      self.attribute_name
      syntax
    • Each instance has its own copy of instance attributes
      • Example:
        self.name = name
        and
        self.age = age
        inside
        __init__()
  • Instance methods are functions defined within a class that operate on instances
    • Defined like regular functions, but with
      self
      as the first parameter
    • Can access and modify instance attributes using
      self
      keyword
      • Example:
        def introduce(self): print(f"My name is {self.name} and I am {self.age} years old.")

Creation of class instances

  • Instances are created by calling the class name followed by parentheses
    • Arguments can be passed to
      __init__()
      to initialize instance attributes
      • Example:
        person1 = Person("Alice", 25)
        creates a
        Person
        instance with
        name
        "Alice" and
        age
        25
  • Instance attributes can be accessed and modified using
    • Syntax:
      instance_name.attribute_name
      • Example:
        person1.name
        accesses the
        name
        of
        person1
  • Instance methods can be called on instances using dot notation
    • Syntax:
      instance_name.method_name(arguments)
      • Example:
        person1.introduce()
        calls the
        introduce
        method on
        person1
  • Multiple instances of a class can be created, each with its own set of instance attributes
    • Example:
      person2 = Person("Bob", 30)
      creates another
      Person
      instance with different attribute values

Instance vs class attributes

  • Instance attributes are specific to each instance of a class
    • Defined within
      __init__()
      using
      self.attribute_name
    • Each instance has its own copy of instance attributes
      • Example:
        self.name
        and
        self.age
        are instance attributes
    • Accessed and modified using dot notation on the instance:
      instance_name.attribute_name
      • Example:
        person1.name = "Alice"
        modifies the
        name
        attribute of
        person1
  • Class attributes are shared by all instances of a class
    • Defined directly within the class, outside of any methods
    • All instances of the class have access to the same class attributes
      • Example:
        species = "Human"
        defined directly in the
        Person
        class
    • Accessed using dot notation on the class itself:
      ClassName.attribute_name
      • Example:
        Person.species
        accesses the
        species
    • Can also be accessed through instances:
      instance_name.attribute_name
      • Example:
        person1.species
        also accesses the
        species
  • Uses of instance attributes:
    • Storing data specific to each instance (
      name
      ,
      age
      , etc.)
    • Representing the state or properties of an object
  • Uses of class attributes:
    • Storing data shared among all instances of a class (
      species
      , default values, etc.)
    • Defining constants or default values for the class
  • Modifying class attributes affects all instances, while modifying instance attributes only affects the specific instance
    • Example: Changing
      Person.species
      affects all
      Person
      instances, but changing
      person1.name
      only affects
      person1

Object-Oriented Programming Concepts

  • : Bundling data and methods that operate on that data within a single unit (class)
  • : Allows a class to inherit attributes and methods from another class
  • : Ability of different classes to be treated as instances of the same class through a common interface

Key Terms to Review (21)

__init__(): __init__() is a special method in Python that is automatically called when a new instance of a class is created. This method is used to initialize the attributes of the instance, allowing you to set initial values for the object when it’s instantiated. By defining __init__(), you provide a clear structure for how objects are created and how their properties are set, which connects directly to the concepts of creating classes, defining methods within them, and accessing instance attributes.
Attribute: An attribute is a characteristic or property of an object, class, or module in object-oriented programming. It is a variable that holds a value and is associated with a specific instance or class.
Class: A class is a blueprint for creating objects, encapsulating data for the object and methods to manipulate that data. It allows for the creation of user-defined data structures.
Class: In the context of programming, a class is a blueprint or template that defines the structure and behavior of objects. It serves as a blueprint for creating objects, which are instances of the class, and encapsulates data and functionality within a cohesive unit.
Class attribute: A class attribute is a variable that is shared among all instances of a class. It is defined within the class but outside any instance methods.
Class Attribute: A class attribute is a variable that is associated with a class itself, rather than with individual instances of that class. It is defined within the class but outside of any methods, and its value is shared across all instances of the class.
Dot Notation: Dot notation is a way of accessing and manipulating the attributes and methods of an object in programming. It involves using the dot (.) operator to reference specific elements within an object.
Encapsulation: Encapsulation is a fundamental concept in object-oriented programming (OOP) that involves bundling data and methods into a single unit, known as a class. It is the mechanism that allows objects to hide their internal implementation details from the outside world, providing a well-defined interface for interacting with the object.
Hierarchical inheritance: Hierarchical inheritance is a type of inheritance in object-oriented programming where multiple derived classes inherit from a single base class. This allows for shared functionality and attributes to be defined in the base class and reused across multiple subclasses.
Inheritance: Inheritance is a fundamental concept in object-oriented programming where a new class is created based on an existing class, inheriting its attributes and behaviors. This allows for code reuse, hierarchical organization, and the creation of specialized classes that build upon the foundation of more general ones.
Instance: An instance is a specific realization or occurrence of a class or object in object-oriented programming. It represents a unique example or instantiation of a general concept or blueprint defined by the class.
Instance attribute: An instance attribute is a variable that is bound to an individual object of a class. It is unique to each instance and can hold different values for different instances.
Instance Attribute: An instance attribute is a variable that is associated with a specific instance or object of a class in object-oriented programming. It stores data that is unique to each instance and can be accessed and modified through the instance.
Instance method: An instance method is a function defined inside a class that operates on instances of that class. It can access and modify the data attributes of the instance.
Instance Method: An instance method is a function defined within a class that operates on the specific instance (object) of that class. It has access to the instance's attributes and can perform actions or return information related to that particular object.
Instances: Instances are individual objects created from a class, each with its own unique data. They enable the use of class-defined attributes and methods in specific contexts.
Method: A method is a function that is defined within a class or an object. It encapsulates a specific behavior or action that an object can perform, allowing it to interact with its data and other objects.
Object-Oriented Programming: Object-Oriented Programming (OOP) is a programming paradigm that focuses on creating objects, which are instances of classes, to represent and manipulate data. It emphasizes the use of encapsulation, inheritance, and polymorphism to create modular, reusable, and maintainable code.
PascalCase: PascalCase, also known as UpperCamelCase, is a naming convention where each word in a compound name starts with a capital letter, and there are no spaces or underscores between the words. This style is commonly used for naming classes, interfaces, and other object-oriented programming constructs.
Polymorphism: Polymorphism is a fundamental concept in object-oriented programming that allows objects of different classes to be treated as objects of a common superclass. It enables objects to take on multiple forms, allowing them to respond to the same method call in different ways.
Self: The 'self' in programming refers to the instance of an object or class that the current method or function is operating on. It is a way for an object to refer to and access its own attributes and methods.
© 2024 Fiveable Inc. All rights reserved.
AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.
Glossary
Glossary