Classes

INPUT · Slides

Settling the contents at the moment of birth

01 / 07

The same handwork every time you make one

Last lesson you made one with Member() and then added the attributes by hand, one at a time. Forget one and the shapes stop matching; the more members, the more lines.

If there is something you always do when you make one, you want that written on the blueprint instead.

02 / 07

Writing __init__

Write def __init__(self): inside the class and the inside of it runs exactly once, at the moment a real one comes into being.

There is no line anywhere that calls it. The point is that Python runs it for you the instant you write Member().

class Member:    def __init__(self):        print("a member came into being")member = Member()print("done")

Result

a member came into being
done

03 / 07

The mark of two underscores

There are two underscores in front of __init__ and two behind. It is not _init_, so take care.

A name wrapped in two underscores is the mark Python uses for "I treat this one specially". Read it as: not a name you call yourself, but a name Python calls at a set moment.

04 / 07

Hanging values on self

The first argument of __init__, self, means the very real one being made right now.

So write self.name = "Aoi" and that real one is given the attribute. By the time it is finished, the contents are already there.

class Member:    def __init__(self):        self.name = "Aoi"        self.years = 3member = Member()print(member.name)print(member.years)

Result

Aoi
3

05 / 07

Passing values in as you make one

As it stands, every one you make comes out identical. To give each one different values, add arguments to __init__.

You pass them inside the () after the class name, as in Member("Aoi", 3). Exactly the arguments of Chapter 3. You do not pass self yourself.

class Member:    def __init__(self, name, years):        self.name = name        self.years = yearsa = Member("Aoi", 3)b = Member("Hinata", 1)print(a.name)print(b.name)

Result

Aoi
Hinata

06 / 07

The same name on the left and the right

self.name = name has the same name on both sides, which looks odd at first. The two meanings are quite separate, though.

  • the self.name on the left … the attribute the real one being made will hold
  • the name on the right … the argument just received

Read it as "copy the value received into the belongings of that real one".

07 / 07

Readable and writable from outside

An attribute put in with self. reads perfectly normally from outside as member.name, and you can overwrite it later.

Default values for arguments work as they always did, so you can decide what happens when nothing is passed. That lets the blueprint hold a default such as "usually year one".

Next lesson we put the things it can do into the box.

class Member:    def __init__(self, name, years=1):        self.name = name        self.years = yearsmember = Member("Minato")print(member.years)member.years += 1print(member.years)

Result

1
2