11.3 Instance methods

3 min readjune 24, 2024

are fundamental to Python classes, allowing objects to interact with their own data. They define behaviors specific to each instance, accessing and modifying attributes using the '' keyword.

These methods come in various types, including constructors, regular instance methods, class methods, and static methods. Each serves a unique purpose, from initializing objects to performing operations on the class itself or providing utility functions.

Instance Methods in Python Classes

Constructor method with parameters

Top images from around the web for Constructor method with parameters
Top images from around the web for Constructor method with parameters
  • [__init__()](https://www.fiveableKeyTerm:__init__())
    special instance method called when creating new instance of class
    • Initializes attributes of instance
    • First parameter always
      self
      refers to instance being created
  • Takes multiple parameters to initialize
    • Parameters defined after
      self
      separated by commas
    • Each parameter assigned to instance attribute using
      self.attribute_name = parameter_name
      • self.name = name
        assigns value of
        name
        parameter to
        name
        attribute of instance
  • included by assigning
    • Default values specified using
      =
      operator after parameter name (
      def __init__(self, name, age=0):
      )
    • If argument not provided when creating instance, default value used

Instance methods and attribute access

  • Instance methods access and modify instance attributes using
    self
    keyword
    • self.attribute_name
      refers to attribute of current instance
    • Modifying
      self.attribute_name
      changes value of attribute for that specific instance
      • self.name = "New Name"
        changes
        name
        attribute of instance to
        "New Name"
  • Can also access directly using class name
    • ClassName.attribute_name
      refers to class attribute
    • Modifying
      ClassName.attribute_name
      changes value of attribute for all instances of class
      • Car.wheels = 5
        changes
        wheels
        attribute for all instances of
        Car
        class
  • If instance attribute has same name as class attribute, accessing
    self.attribute_name
    refers to instance attribute, overriding class attribute for that instance
  • occurs when an instance method is called on an object

Types of class methods

  • Instance methods defined within class and operate on individual instances
    • Take
      self
      as first parameter referring to instance on which method is called
    • Access and modify instance attributes using
      self
      • def drive(self): self.speed += 10
        increases
        speed
        attribute of instance by
        10
  • Class methods defined using
    [@classmethod](https://www.fiveableKeyTerm:@classmethod)
    decorator and operate on class itself
    • Take
      [cls](https://www.fiveableKeyTerm:cls)
      as first parameter referring to class
    • Access and modify class attributes using
      cls
      • @classmethod def from_string(cls, car_str): ...
        creates instance of class from string representation
    • Often used for alternative constructors or methods that operate on class as a whole
  • Static methods defined using
    [@staticmethod](https://www.fiveableKeyTerm:@staticmethod)
    decorator and do not have access to instance or class attributes
    • Do not take
      self
      or
      cls
      as parameters
    • Independent of instances and class, used for utility functions or operations that don't require access to instance or class data
      • @staticmethod def miles_to_kilometers(miles): return miles * 1.60934
        converts miles to kilometers without needing instance or class

Object-Oriented Programming Concepts

  • : Instance methods help achieve encapsulation by bundling data and methods that operate on that data within a class
  • : Subclasses inherit instance methods from their parent classes, allowing for code reuse and specialization
  • : Instance methods can be overridden in subclasses, enabling different implementations of the same method name across related classes

Key Terms to Review (17)

__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.
@classmethod: @classmethod is a special method in Python that allows a method to be called on the class itself, rather than on an instance of the class. This method can access and modify class-level attributes and perform operations that are specific to the class, rather than to a particular instance of the class.
@staticmethod: @staticmethod is a Python decorator that allows you to define a function within a class that can be called without an instance of the class. It is a way to create utility functions that are associated with a class but do not require an instance of the class to be called.
Class attributes: Class attributes are variables that are shared across all instances of a class, defined within the class but outside any instance methods. They serve as properties or characteristics of the class itself, rather than of individual objects created from the class. This means that when you change a class attribute, it affects all instances of that class, making them useful for storing values that should be consistent across all objects.
Cls: The 'cls' term in the context of instance methods refers to the class object itself, which is automatically passed as the first argument to instance methods. It allows the method to access and manipulate the class's attributes and behaviors.
Default Values: Default values refer to the predetermined values that are assigned to parameters or variables when they are not explicitly provided. These default values serve as fallback options, ensuring that the code can still function even when certain inputs are missing.
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 Attributes: Instance attributes are the variables or properties that belong to a specific instance or object of a class in object-oriented programming. They define the unique characteristics and state of each object created from the class.
Instance Methods: Instance methods are functions defined within a class that operate on the specific instances, or objects, created from that class. They provide a way for objects to interact with and manipulate their own data and behavior.
Method Invocation: Method invocation is the act of calling a specific function or behavior defined within an object in a programming language. It is a fundamental concept in object-oriented programming that allows objects to interact with one another and perform various tasks.
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.
Optional Parameters: Optional parameters are function parameters that are not required to be provided when the function is called. They allow for more flexible and versatile function usage by enabling the caller to decide which parameters to include or exclude based on their specific needs.
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