Concepts / Modifying Object State with Methods

Modifying Object State with Methods

The central question for every instance method is: which object is this method working with? The self parameter provides that answer.

  • Programming

Behavior Belongs with Data

A method is a function that belongs to a class. It combines behavior with the data represented by an object. When a method is called on an instance, Python automatically passes that particular object into the method through the parameter named self.

Key point

The central question for every instance method is: which object is this method working with? The self parameter provides that answer.

A Method Definition

python
defstarts a functiondefinitionsay_himethod nameselfreceives the calling objectprint("Hi!")method bodydefinesacceptsidentifies the object for
Which parts identify the method, receive the object, and contain the behavior?

The def keyword begins the method definition. The method name comes next, followed by parentheses containing self. The indented statements form the method body. Even when the method needs no information from the caller, self remains in the definition because the method still needs to receive the object on which it was called.

Tracing the Calling Instance

pPerson instancesay_himethodself = pduring p.say_hi()qPerson instanceself = qduring q.say_hi()callscallsreceives p forreceives q for
How does the same method know which object it is working with when different instances call it?

Suppose p and q are two Person instances. In p.say_hi(), self refers to p. In q.say_hi(), self refers to q. The method definition is shared by the class, but the automatically supplied self value changes according to the instance before the dot.

Code walkthrough
class Person:
    def say_hi(self):
        print("Hi!")

p = Person()
p.say_hi()

q = Person()
q.say_hi()
  1. 1
    Python creates p from Person and then evaluates p.say_hi().
  2. 2
    The method receives p through self and executes its print statement.
  3. 3
    Python creates q from Person and then evaluates q.say_hi().
  4. 4
    The method receives q through self and executes the same print statement.
  • The class defines one method named say_hi.
  • p is created as a Person instance.
  • p.say_hi() calls say_hi with p automatically supplied as self.
  • q is another Person instance.
  • q.say_hi() calls the same method with q supplied as self.
Output
Hi!
Hi!

Changing Object State

A method can do more than print text. Because self identifies the object being used, the method can work with that object's attributes and perform an action on its behalf. The following generated example illustrates a method that changes an attribute representing the object's state.

Code walkthrough
class Counter:
    def increase(self):
        self.value = self.value + 1

counter = Counter()
counter.value = 0
counter.increase()
print(counter.value)
  1. 1
    The method call selects counter as the object that should be changed.
  2. 2
    Python supplies that object as self.
  3. 3
    The assignment in the method changes the value associated with self.
  4. 4
    Since self is counter for this call, counter.value becomes 1.
  • Counter defines an increase method with only self.
  • counter.value begins at 0 in this example.
  • counter.increase() supplies counter as self.
  • The method uses self.value to change the value belonging to counter.
  • The final print displays the changed value.
Output
1
countervalue = 0increasemethod callcountervalue = 1invokeschanges state to
What changes inside the Counter object when increase is invoked?

Before the call, the generated example gives counter a value of 0. During counter.increase(), self refers to counter, so self.value identifies the value belonging to that object. After the method runs, the object's value is 1. This is the basic pattern behind modifying object state: a method receives the object through self and performs an operation using that object.

Calling Without Extra Arguments

Method definitionCallAdditional caller data
def say_hi(self):p.say_hi()None
def greet(self, name):p.greet("Mina")name receives "Mina"

Both methods require self in their definitions. A method may also define additional parameters when the method needs information from the caller.

A method can take no additional parameters beyond self. In that case, the caller writes the method name followed by empty parentheses, as in p.say_hi(). The empty parentheses do not mean that self is missing; Python supplies self automatically. They mean that the caller is not supplying any other argument.

Edge case

A method can also be invoked directly on a class constructor, as in Person().say_hi(). Person() creates a temporary Person object, and say_hi is called on that object immediately. This approach is useful when the object does not need to be stored for later use.

python
Output
Hi!
Hi!

Mistakes with self

  • Common mistake

    Leaving self out of the method definition when the method takes no other parameters.

    What it looks like
    def say_hi():
    Why it fails

    Every method definition needs self so Python has a parameter through which it can pass the object that called the method.

    Do this instead
    Write def say_hi(self):
  • Common mistake

    Assuming the caller must type self as an argument.

    What it looks like
    p.say_hi(p)
    Why it fails

    Python automatically passes p as self when the method is called with dot notation.

    Do this instead

    Write p.say_hi() when the method takes no additional parameters.

  • Common mistake

    Treating self as one permanently fixed object.

    What it looks like

    Assuming self always refers to p, even during q.say_hi().

    Why it fails

    self refers to the specific instance used for the current call.

    Do this instead

    Trace the object before the dot: self is p for p.say_hi() and q for q.say_hi().

  • Common mistake

    Using a separate function instead of a method when the behavior belongs with the class data.

    What it looks like

    Defining behavior outside the class even though it operates on the object's state.

    Why it fails

    Methods bundle behavior with data and make class-based code more organized and maintainable.

    Do this instead

    Define the behavior inside the class when it belongs to the objects created from that class.

Best practice

When reading an instance method call, identify the object before the dot first. Then substitute that object mentally for self while tracing the method body. This makes it easier to determine which object's attributes or state the method can access or modify.

Trace the Method Call

EASY

Consider the generated Counter example. Trace counter.increase() in order. Identify the object selected by the expression, the value received by self, and the state change that occurs after the method body runs.

Hints
  • Look at the object before the dot.
  • The method definition contains only self, so the caller supplies no additional argument.
  • The method changes the value associated with self.
Worked example

Tracing p.say_hi()

A Person class defines say_hi(self), and the call p.say_hi() is made. What does self refer to, and what does the method do?

  1. 1
    Select the instance

    The object before the dot is p, so p is the instance on which the method is called.

  2. 2
    Supply self

    Python automatically passes p to the method through its self parameter.

  3. 3
    Run the body

    The method body executes with self referring to p. In the source-shaped say_hi example, the body prints Hi!.

  4. 4
    Check for a return value

    The example method performs the printing action and does not return a value.

Result

During p.say_hi(), self refers to p, and the method performs its print action on behalf of that object.

Summary

  1. 1
    A method is a function that belongs to a class.
  2. 2
    Every method definition includes self, even when there are no additional parameters.
  3. 3
    Python automatically passes the instance used in a dot-notation call as self.
  4. 4
    The same method can operate on different objects because self changes with the calling instance.
  5. 5
    Methods bundle behavior with data and can perform actions or modify an object's state.

At a glance

  • A method is a class-owned function that receives its calling object through self.
  • self is required in every method definition because it identifies the object the method works with.
  • In p.say_hi(), Python supplies p as self automatically.
  • A method with only self needs no additional argument from the caller.
  • Methods can use the object identified by self to perform behavior and modify object state.

Related concepts

More concepts starting with M