Defining classes and constructors
20-minute lesson · module-classes-02
You are previewing this course as a guest
Read anything and run any exercise you like. It all runs in your own browser, so nothing here is saved: no XP, no progress, and the AI tutor needs an account. Sign in and your work starts counting.
Defining classes and constructors
20-minute lesson · module-classes-02
- Write a class statement that defines a new type.
- Define an `__init__` constructor that sets up instance attributes.
- Create instances and read their attributes with dot notation.
- Explain the role of `self` as the instance being operated on.
Source attribution
Status: adapted
How to Think Like a Computer Scientist: Interactive Edition — source · Classes and Objects - the Basics / User-Defined Classes / Improving our Constructor
Adaptation notes. Reading rewritten in our voice. The worked class models an Iowa State Student with a name and a credit total. Hidden tests construct instances and check that the constructor stored the right attributes.
License notes. Original chapter is GNU FDL 1.3 (Brad Miller and David Ranum). No verbatim text from the original is reproduced here.