liveBook · Manning

Self parameter

As explained in Python Workout: 50 ten-minute exercises

self is the conventional first parameter of a Python instance method that refers to the instance on which the method was invoked.

In a Python instance method, self names the instance on which the method was invoked. Python passes that instance as the method’s first argument, so __init__ can create attributes such as self.name or self.flavor. section 9.2 section 9.5

Use self to make instance behavior and inheritance work together:

  • Assigning self.attribute creates or updates data attached to the current instance; defining initial attributes in __init__ keeps object structure readable. section 9.5
  • self is a naming convention rather than a reserved word. Another first-parameter name may run, but Python developers and tools expect self. section 9.2
  • self.max_scoops uses instance-then-class lookup, allowing one add_scoops method to use Bowl.max_scoops or BigBowl.max_scoops according to the object. section 9.17
  • self.__class__.__name__ can identify the concrete class of an inherited instance, while super().__init__ delegates initialization to the appropriate parent method. section 9.27

Creating and reading an instance attribute

class Person: def __init__(self, name): self.name = name p = Person('myname') print(p.name) section 9.5

class Foo():
   def __init__(self, x):
       self.x = x

Inspect the compact Foo example to see self.x created during initialization and later accessed through the instance. section 9.5

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains parameter binding, attribute creation, lookup, inheritance, and object initialization, while stopping short of detailed method-binding internals.
Examples
Demonstrates Scoop and Person initialization, Foo attribute access, Bowl lookup, and inherited Animal representations.
What it assumes
Assumes familiarity with Python functions and classes while building instance attributes and method-instance relationships through examples.
What you can do after
Apply self in instance methods to initialize attributes, access object state, and reuse behavior across subclasses.
How it connects
Connects instance methods to classes, inheritance, attributes, __init__, super(), and __class__.

Also explained in

Compare how 3 books explain self parameter →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.