01 / 07
Classes
INPUT · Slides
Write a blueprint, make a real one
02 / 07
Writing class
Put a name after class and close the line with a :. From the next line, indent by four spaces and write the inside. The same shape as if and def.
There is nothing to put inside yet, and Python will not let the inside be empty. Put down one line of pass, which says "do nothing", and move on.
class Member: passprint("blueprint made")Result
blueprint made
03 / 07
Names start with a capital
The Python convention is for a class name to start with a capital letter. That way you can tell member, the container variable, from Member, the blueprint, at a glance.
Make the name what you would call one of them. Even a blueprint for handling a crowd of members is Member, not Members.
class Member: passclass Product: passprint("two blueprints")Result
two blueprints
04 / 07
Making a real one from the blueprint
Stare at a cake tin all you like and no cake appears. Writing the blueprint on its own brings not one scrap of real data into being.
To make a real one, call the class name with () after it. What comes out is called an instance.
class Member: passmember = Member()member.name = "Aoi"print(member.name)Result
Aoi
05 / 07
Values go in and out through a dot
A value an instance holds is called an attribute. Reading and writing both use the shape instance.name.
What was member["name"] with a dictionary is member.name with a class. No square brackets and no quotes, which reads more easily.
class Member: passmember = Member()member.name = "Aoi"member.years = 3print(member.name)print(member.years)Result
Aoi 3
06 / 07
As many as you like from one blueprint
Instances made from the same class are separate containers. Change an attribute on one and the other stays as it was.
One cake tin, and the cakes that come out of it are each their own.
class Member: passa = Member()a.name = "Aoi"b = Member()b.name = "Hinata"print(a.name)print(b.name)Result
Aoi Hinata
07 / 07
You are still putting it in by hand
At the moment you make one with Member() and then write .name = ... yourself. Five items means five lines, and ten members means fifty.
And nothing stops you when you forget one, so you are no better off than you were with dictionaries. The machinery for having the contents ready as it is made turns up next lesson.