More Python Class Methods
MIT 6.100L Intro to CS and Programming using Python, lecture 18, explained in plain English
Want this lecture to stick? In LessonBound you get checked practice questions for every part, can ask about anything you don't get, and can listen with your screen off. Free, no ads.
Learn this lecture freeWatch or read the original lecture: MIT OpenCourseWare.
Part 1 · 0:00–10:00
This part shows how to design a class in Python, from its name and parent to its __init__ setup and its distance method.
Key ideas
- There are two ways to look at a class. The implementer writes the class's design, and the user creates objects from it and runs methods on them. 1:13
- A class starts with the keyword class and a name you choose. The parentheses hold the parent class, and object is the most basic parent, so the new class can do everything a plain Python object can do. 3:03
- The __init__ method is the constructor. It says how to build a new object, and any variable set with self. (like self.x) becomes a data attribute that every object of that class has. 5:38
- The distance method takes self and one other coordinate, uses Pythagoras to find the gap between the two points, and returns a number. 6:46
- The lecture is about to add a second method, to_origin, which will do something different from distance. 9:37
Words to know
- instance
- One specific object made from a class. For example, one particular coordinate with x=3 and y=4.
- method
- A function that belongs to a class and works on objects of that class.
- attribute
- A piece of information stored inside an object, such as x or y in a coordinate.
- self
- The name a method uses to refer to the object it is being run on. It is filled in automatically when the method runs.
Example
Think of a class as a cookie cutter and each instance as one cookie. The cutter sets the shape and what every cookie will have, but you can make many cookies that each differ a little. Writing the class is like making the cutter, and using the class is like pressing out cookies.
3 checked practice questions for this part are in the app.
Part 2 · 10:00–20:00
This part shows how to write a method that changes an object's values, and how a class can be built from other objects like a coordinate point.
Key ideas
- The to_origin method resets a point's x and y values to 0. It does not return anything; it changes the object it is called on. 10:00
- One class can make many objects. Each object has the same kinds of values, but the actual numbers can be different. 10:41
- A class is a blueprint. Inside the class, self stands for the object being made or used, and anything set with self. is a data attribute that every object of that type has. 13:36
- When designing a circle class, the lesson uses a radius and a center. The center is itself a coordinate object, so one object is built from another. 15:26
- The init method, which runs when an object is created, can check that the inputs are the right type. If they are wrong, it raises a ValueError. Python does not check types on its own. 19:05
Words to know
- method
- A function that belongs to an object or a class. You call it on an object, like c.to_origin().
- dot notation
- Writing the object name, then a dot, then a data attribute or method name, such as c.x or c.distance. The thing before the dot is the object.
- data attribute
- A value stored inside an object, such as x or y for a coordinate. Each object of a type has its own copy.
- constructor
- The step where you create a new object by writing the class name and passing in its starting values. The init method runs during this step.
Example
Think of a class as a blank paper form for a new library card, with boxes for name and address. Each filled-out card is an object. Two cards use the same form, but each has different names in the boxes. If a clerk checks that a box holds a valid address before accepting the card, that is like init checking types.
3 checked practice questions for this part are in the app.
Part 3 · 20:00–30:00
This part shows how to check a class's inputs before building an object, how a circle method can test whether a point is inside it, and how to plan a new fraction class.
Key ideas
- Check the inputs first. If the radius is not an integer, the code raises a ValueError, which stops the program before the object is built. The object only gets created when every check passes. 20:00
- A circle method can test whether a point is inside. It finds the distance from the point to the circle's center, then compares that distance to the radius. A smaller distance means the point is inside. 21:49
- The method uses a distance method that was already written for the coordinate class. Reusing that code saves work, as long as the point passed in is a coordinate object. 22:55
- The order of the two points does not change the distance. So calling the distance method on either point gives the same answer, and the two is_inside versions behave the same way. 26:47
- Before writing a fraction class, decide what data will represent it. A fraction can be stored as two integers: a numerator (the top number) and a denominator (the bottom number). 28:38
Words to know
- raise a ValueError
- Stop the code and report that the input was wrong. ValueError is the name of the error Python uses for a bad value.
- method
- A function that belongs to a class. You call it on an object using a dot, such as point.distance(other).
- docstring
- A short note written inside a class or method that explains what it is for and what inputs it expects.
- numerator
- The number above the line in a fraction. The number below the line is the denominator.
Example
Think of a bouncer at a door who checks your ID before letting you in. If the ID is wrong, you never get inside, and the same idea applies here: the code checks the inputs before it builds the object. A point is inside a circle if it is closer to the center than the edge, like a dog on a leash that stays within reach of its owner.
3 checked practice questions for this part are in the app.
Part 4 · 30:00–40:00
This part shows how to write a SimpleFraction class with methods that multiply, add, and flip fractions, and how Python connects an object to the method it calls.
Key ideas
- The init method sets up a new SimpleFraction object. The user passes in a numerator and a denominator, and these are saved as the data attributes self.num and self.denom. 30:21
- When you call a method with a dot, the object before the dot is mapped to self. Everything in the parentheses is mapped to the other parameters, such as oth. 31:09
- To multiply two fractions, multiply the numerators together and the denominators together. Adding is similar but uses a criss-cross step for the new numerator. Both methods return a float, which is a decimal number. 31:30
- The get_inverse method returns a float for 1 over the fraction, without changing the object. The invert method changes the object itself by swapping its numerator and denominator, and it returns nothing. 36:10
- Python can only divide plain numbers, so the code has to divide self.denom by self.num, which are integers, instead of dividing 1 by the whole SimpleFraction object. 38:02
Words to know
- method
- A function that belongs to an object. You call it with a dot after the object, like f1.plus(f2).
- self
- The name used inside a method for the object that the method was called on. It is the thing before the dot.
- data attribute
- A value stored inside an object, such as the numerator or denominator of a fraction.
- float
- A number with a decimal point, such as 0.1875 or 1.3333.
Example
Think of a box labeled with a fraction, like 3 over 4. When you ask the box to flip itself, the top and bottom numbers swap, so it now says 4 over 3. The box is the object, and the instructions for flipping it are the method.
3 checked practice questions for this part are in the app.
Part 5 · 40:00–50:00
This part explains how Python turns shortcuts like + and print into special methods you can write yourself, so your own objects can be printed and used with operators.
Key ideas
- Operators like +, *, and print are shorthand. Behind the scenes, each one runs a method, and these methods have special names with double underscores on each side. 43:45
- Python does not know how to use an operator with your object unless you write the method for it. Without that method, multiplying two of your objects gives an error. 43:04
- By default, printing your object only shows its type and memory location. To get a useful display, you write the __str__ method, which returns a string that Python then prints. 45:32
- The __str__ method should return a string, not print it. You decide how the string looks, for example by joining pieces together with concatenation. 47:42
- The object c you print is a real object, not the class definition. Python uses the __str__ method you wrote to decide how that object looks when printed. 49:46
Words to know
- dunder method
- A special method with double underscores on each side of its name, such as __str__. Python runs it automatically when a certain shortcut or event happens.
- operand
- A value that an operator works on. In 'a * b', a and b are the operands.
- concatenation
- Joining pieces of text together into one longer piece of text.
- instance
- One real object made from a class. For example, c is one coordinate object made from the coordinate class.
Example
Think of a shop where the sign says 'Coffee' but the person behind the counter knows the full order it stands for. The short word is the shortcut, and the shop decides what the full order is. In Python, the shortcut is the operator, and the class you write decides what it does for your object.
3 checked practice questions for this part are in the app.
Part 6 · 50:00–1:00:00
This part shows how to make the fraction class work with Python's built-in operators and printing by writing special methods, starting with how it displays and how multiplication works.
Key ideas
- In Python, everything is an object, including the class you define. A class like Coordinate has the type type, and you can check an object's type with type() or isinstance(). 50:46
- A __str__ method controls how an object looks when you print it. It takes only self, and it helps with debugging because you can see the fraction's numbers when you print it. 52:16
- The star operator between two fractions runs a method called __mul__ behind the scenes. The object before the star is self, and the object after the star is other. 57:14
- The new __mul__ returns a fraction, not a float, so you can keep working with fraction objects throughout your code. 58:15
- The lesson improved the display so a fraction with denominator 1 shows only the numerator, but the lecturer then said that version would not be used for the rest of the lecture. 54:25
Words to know
- dunder method
- A special method whose name starts and ends with two underscores, like __str__ or __mul__. Python calls it automatically when you use certain operators or actions on your object.
- isinstance
- A built-in Python function that checks whether an object belongs to a certain type. For example, isinstance(3, int) gives True.
- concatenation
- Joining strings together end to end, like putting pieces of text side by side to make one longer piece of text.
- float
- A number with a decimal point, such as 0.75. The old times method returned one of these.
Example
Think of a fraction like 5/1 as a number that should look like 5, not 5/1, when shown to a person. The lecture made the str method check whether the denominator is 1, and if it is, print only the numerator. This matches the lesson's example where a fraction 3 over 1 prints as just 3.
3 checked practice questions for this part are in the app.
Part 7 · 1:00:00–1:10:00
This part shows how Python's shorthand symbols, like *, secretly run special class methods, and how a fraction class can convert itself to a float and reduce itself to simplest form.
Key ideas
- When Python sees the * symbol between two fraction objects, it asks the fraction class whether it has a __mul__ method, and runs that method to do the multiplication. 1:00:00
- Special methods with double underscores, like __mul__, are called dunder methods. Shorthand symbols hide them so you don't have to call them with dot notation, which the lecturer calls non-Pythonic and verbose. 1:01:20
- The __float__ method tells Python how to turn a fraction into a float. It divides the numerator by the denominator, so 3/16 becomes 0.1875. 1:05:25
- Multiplying fractions can leave them unreduced, such as 2/12, even though the value can be written more simply as 1/6. The lecturer adds a method to fix this. 1:07:12
- The reduce method handles three cases: a denominator of 0 returns None, a denominator of 1 returns the numerator, and otherwise both numbers are divided by their greatest common divisor. 1:08:40
Words to know
- dunder method
- A special method whose name starts and ends with double underscores, such as __mul__. Python runs it behind the scenes when you use a symbol or built-in action.
- gcd (greatest common divisor)
- The largest number that divides evenly into two numbers. Dividing the top and bottom of a fraction by it simplifies the fraction.
- float
- A number with a decimal point, such as 0.1875.
- Pythonic
- Written in the clean, short, natural style that experienced Python programmers use.
Example
Writing a * b is like saying 'multiply' in a short phrase. You don't spell out every step, but the steps still happen behind the scenes, just as a shorthand note still stands for the full sentence it replaces.
3 checked practice questions for this part are in the app.
Part 8 · 1:10:00–1:17:19
This part explains why a class method should always return the same type of object, and why bundling data and behavior together keeps code organized.
Key ideas
- The reduce method returned a plain whole number (an int) when the denominator was 1, but a fraction otherwise. Mixing these two types caused Python to fail when multiplying them. 1:11:03
- The fix is to make the method always return a fraction object, even when the denominator is 1. Then every result has the same type and can be used in the same way. 1:12:50
- Returning new objects of the same class is a new idea in this lesson. The method builds and hands back a fresh object instead of just a number. 1:14:14
- Bundling data and behaviors together in a class makes objects predictable. A coordinate object always has an x and a y, so other code can rely on it. 1:16:28
- Decomposition (splitting code into separate parts) and abstraction (hiding details behind a clear description) work for classes the same way they worked for functions. 1:16:05
Words to know
- method
- A function that belongs to an object and works on that object's own data. You call it with a dot, like c.reduce().
- int
- Short for integer. A whole number with no fraction part, like 4 or 7.
- decomposition
- Breaking a big job into smaller, separate pieces so each piece can be reused and understood on its own.
- abstraction
- Hiding the messy details of how something works and giving a clear description of what it does instead, such as a docstring.
Example
Think of a shop that sells both loose apples and apple boxes, but sometimes hands you a bare number instead of a box. Your cart would break whenever you mixed the two. If the shop always hands you a box, even a box with one apple, everything in your cart works the same way.
3 checked practice questions for this part are in the app.
← Lecture 17: Python Classes · Lecture 19: Inheritance →
Notes written by AI (Claude) from the lecture's official transcript, so check anything important against the lecture. MIT OpenCourseWare · CC BY-NC-SA 4.0 · not affiliated with or endorsed by MIT. These notes are shared under the same license.
LessonBound · Free lecture notes · Privacy · Terms · New York