← Back to course
Python 11-12 / Week 02 / Tuesday
2/6
Week 02 Β· Classes and Objects

Tuesday

What self means
// A class is a blueprint, and each object keeps its own state
⏱ about 30 min

Tuesday: What Self Means

Comet points at the word self, which appears in every line of __init__. "Who is self?" she asks. "I never pass it in. I only give three values."

Wren counts the parameters on his clipboard. "What does the evidence say?" he asks. "The def line has four names, but the call has three values. Something fills the first one."

Nova projects a call, Sample("S05", "granite", 30), and draws arrows from each value into __init__. "How can I help?" she asks. "Follow the arrows. One of them comes from Python itself."

Comet leans in. "Lead programmer, trace it with us."

A method gets the object as self

A method is a function defined inside a class. Called on an object, it gets that object as its first argument, usually named self.

__init__ is a method too. When you call Sample(...), Python passes the brand new object to __init__ as self, then your arguments after it.

Default values for row and col

Some samples have no spot on the field yet. This step gives row and col default values of 0, so a call can leave them out.

S05 granite is made-up data from the FieldSim story, a sample that has not been placed on the field.

# sample_defaults.py
class Sample:
    """One sample token from the test field."""

    def __init__(self, label, kind, grams, row=0, col=0):
        self.label = label
        self.kind = kind
        self.grams = grams
        self.row = row
        self.col = col


s01 = Sample("S01", "basalt", 42, 0, 2)
s05 = Sample("S05", "granite", 30)
print(s01.row, s01.col)
print(s05.row, s05.col)
print(s05.label, s05.grams)
Parameter of __init__Value in Sample("S05", "granite", 30)Where it came from
selfthe new Sample objectPython passes it in
label"S05"first argument
kind"granite"second argument
grams30third argument
row0default
col0default
PREDICT SAMPLE_DEFAULTS.PY
  • Read the question.
  • Tap your answer.
What does print(s05.row, s05.col) show?
What does print(s01.row, s01.col) show?
0 2
0 0
S05 30
STEPS OF SAMPLE("S05", "GRANITE", 30)
  • ?Each self line stores a value on the new object
  • ?The new object is stored in the name s05
  • ?label, kind and grams get the three arguments
  • ?row and col take their default of 0
  • ?Python makes a new Sample object
  • ?Python runs __init__ with the new object as self
WHY THIS EXERCISEThe new object is made, __init__ fills its attributes through self, and only then does the name s05 refer to it.

Calling a method

This step adds a method of its own, weight_line(). Watch the last two calls: they do the same job in two ways.

# self_demo.py
class Sample:
    def __init__(self, label, kind, grams, row=0, col=0):
        self.label = label
        self.kind = kind
        self.grams = grams
        self.row = row
        self.col = col

    def weight_line(self):
        return f"{self.label} weighs {self.grams} g"


a = Sample("S01", "basalt", 42, 0, 2)
b = Sample("S02", "quartz", 18, 2, 4)
print(a.weight_line())
print(b.weight_line())
print(Sample.weight_line(b))
TRACE SELF_DEMO.PY
  • Read the question.
  • Tap your answer.
In b.weight_line(), what is self?
Why do the last two lines match?

self is a name, not a keyword

The name self is only a convention. It has no special meaning to Python, as this run shows.

Every Python programmer reads self, though, so this course always uses it.

# not_self.py
class Tag:
    def __init__(me, label):
        me.label = label

    def show(me):
        return "Tag " + me.label


print(Tag("S03").show())

An object's state is its attributes and their values at a given time. The object has a has-a relationship with them: s05 has a grams of 30.

A constructor sets the starting state. It should give every instance variable a starting value, as __init__ does for all five.

At your computer
1. Type sample_defaults.py, save it and run it.
2. Make s06 = Sample("S06", "shale", 51, 1, 4). Predict what print(s06.row, s06.col) shows, then run it.
3. Type self_demo.py and run it. Add a line that calls Sample.weight_line(a). Predict, then run it.
4. In weight_line, rename self to me in both places. Run it and check the output is the same. Then change it back.
StatementTrue or false?
A method gets the object it was called on as its first argument.?
self is a keyword that Python reserves.?
A constructor should give every instance variable a starting value.?
A default value is used even when the call gives that argument.?
WHY THIS EXERCISEself is only the usual name for the first parameter, which holds the object. A default fills in only when a value is left out.

Now you know who self is. Tomorrow is Sim Lab: you will type the real sample.py for FieldSim.

← Monday