1. Home
  2. Explore
  3. Computer Science
  4. Object-Oriented Programming in Python

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Object-Oriented Programming in Python

Speaker 1Speaker 2

Object-Oriented Programming in Python

16:28
0:00-16:28
  1. Anna

    Welcome to our episode on object-oriented programming in Python. The central idea is that as programs grow, it helps to organize related data and behavior together. We’ll build up to that idea through a student example, then look at classes, methods, validation, inheritance, and even giving operators like plus a meaning for our own objects.

  2. Michael

    And it helps to place object-oriented programming among other programming styles. Procedural programming is the step-by-step approach we’ve mostly used: write functions and instructions that run in sequence. Python also supports functional programming features, such as passing functions around. Object-oriented programming is another way to structure a solution, especially useful as programs become larger and more complicated.

  3. Anna

    Let’s start with a simple student program. We ask for a student’s name and Hogwarts house with input, store each answer in a variable, and print a sentence like, “Harry from Gryffindor.” That works, but it leaves all the logic together in one place.

  4. Michael

    A first improvement is to put the work into functions. We might have a main function that calls get_name and get_house, then prints the result. Each smaller function hides its implementation details: main can call get_name without needing to know exactly how that function prompts the user.

  5. Anna

    We can take the abstraction one step further. Instead of separate functions for the name and house, define get_student to collect both. The function now needs to return the student’s two pieces of information. Python lets us return them separated by a comma, and the caller can unpack them into two variables.

  6. Michael

    That comma-return is often described as returning multiple values, but more precisely Python returns one tuple containing those values. A tuple is a collection, like a list in some ways, but it is immutable: once created, its items can’t be reassigned. You can still access its items by index, such as student[0] for the first item and student[1] for the second.

  7. Anna

    That immutability can be useful defensively. If a group of values should not change, a tuple makes accidental changes less likely. But when we try to correct a student’s house by assigning to student[1], Python raises a TypeError because tuples don’t support item assignment.

  8. Michael

    If the values do need to change, a list is a better fit. A list also holds a collection of values and can be indexed with square brackets, but it is mutable. We can change an item, so we can correct a house after the list is created.

  9. Anna

    A dictionary gives us another option. Rather than remember that index zero means name and index one means house, we can store named keys like 'name' and 'house'. Then we retrieve values with those keys, which is more expressive, especially when a record has many fields.

  10. Michael

    Dictionaries are mutable too, so we can update the house using the 'house' key. One small syntax trap: if an f-string is already delimited by double quotes, using double quotes again inside its expression can confuse Python. Use single quotes for the dictionary keys inside, or change the outer quotation marks.

  11. Anna

    So tuples, lists, and dictionaries are all ways to group data, with different tradeoffs. A tuple is immutable and accessed by positions; a list is mutable and also accessed by positions; a dictionary is mutable and accessed by meaningful keys. But what if Python doesn’t have exactly the kind of data type we want?

  12. Michael

    That’s where classes come in. A class is a blueprint or mold for a kind of data that we define ourselves. In the student example, we can define a Student class and give it attributes such as name and house. An object is a particular instance created from that class.

  13. Anna

    The class is the definition; the object is a specific student made from it. We create an object by calling the class, much like a function: student = Student(). Then dot notation lets us set or access attributes, such as student.name and student.house.

  14. Michael

    A class can define a special method named __init__. Python calls it when an object is initialized, so it gives us one standard place to set up each student. We can have it accept name and house, then assign them to the new object.

  15. Anna

    That’s where self comes in. An instance method’s first parameter is conventionally named self, and Python supplies a reference to the current object. So self.name = name stores the incoming name on that particular student, and self.house = house stores that student’s house.

  16. Michael

    When we write Student(name, house), Python creates an object and invokes its initialization method with the supplied values. Strictly speaking, Python’s __new__ method is responsible for creating the object, while __init__ initializes it. In everyday Python programming, we generally define __init__ and let Python handle the object-creation part.

  17. Anna

    This gives us a consistent structure: every Student object has the attributes we chose, while each object can hold different values. Classes can store different kinds of values too, but our example uses strings for name and house.

  18. Michael

    They can also contain methods, which are functions defined inside a class. We’ve already met special methods—methods with names like __init__ that Python calls for particular purposes. We can use another one, __str__, to decide what a Student should look like when converted to a string.

  19. Anna

    Without a custom __str__, printing an object tends to show a technical representation, including its class and a memory-related address. That may be useful to a developer in some contexts, but it’s not a friendly description for a program’s user.

  20. Michael

    If we define __str__(self) to return an f-string like “Harry from Gryffindor,” then print(student) can display that readable description. Python calls __str__ when something such as print needs the object as a string, and self gives the method access to that specific student’s attributes.

  21. Anna

    There’s a related method called __repr__. The distinction described here is that __repr__ is generally intended as a developer-oriented representation, while __str__ is usually more user-friendly. Both can be customized.

  22. Michael

    Now let’s talk about validating data. We don’t want to create a student with a blank name or accept a house that isn’t one of Gryffindor, Hufflepuff, Ravenclaw, or Slytherin. We could put those checks in an outside get_student function, but then student-related logic would be scattered away from the Student class.

  23. Anna

    Object-oriented design encourages encapsulation: keep related data and functionality together. We can put validation in the class’s initialization process, so the class controls what it accepts. If a name is missing, we can raise a ValueError with a message such as 'missing name'; for an invalid house, raise a ValueError saying 'invalid house'.

  24. Michael

    Raising an exception signals that something has gone wrong without necessarily exiting the entire program. The caller can use try and except to handle it. That’s different from calling sys.exit, which would stop the program abruptly, and it’s not useful to return None after an invalid object has already been created.

  25. Anna

    A class can take more data if the model requires it. For example, we could represent first, middle, and last names as separate arguments and attributes, or perhaps store a collection of names. The right design depends on what the program needs; the point is that a class gives us a place to define that structure.

  26. Michael

    We can also make a parameter optional by giving it a default value in the method’s signature. And if we need a more specialized error, Python lets us define custom exception types too. The key idea here is that class methods are still Python functions, even when Python calls a special one automatically.

  27. Anna

    But there’s a weakness in validation that only happens in __init__. After the object is created, code could still do student.house = 'Number Four, Privet Drive' and bypass the original check. The class’s attributes are accessible through dot notation, so we need a way to control changes as well.

  28. Michael

    Python properties provide that control. A property lets us define a getter and setter so access that looks like an attribute can run our own code. We use the @property decorator above the getter, then a setter decorator such as @house.setter above the setter.

  29. Anna

    The getter takes self and returns the stored house. The setter takes self plus the new house value, checks whether it’s valid, raises ValueError if it isn’t, and stores it if it is. Because the assignment uses student.house = value, Python routes that assignment through the setter.

  30. Michael

    This also lets __init__ use self.house = house, so the initial value goes through the same validation. The underlying storage uses a differently named instance variable, conventionally _house, to avoid colliding with the property named house. The getter returns self._house, and the setter assigns to self._house.

  31. Anna

    We can make name a property in the same way, rejecting an empty value. That gives us one place to maintain each rule, rather than duplicating validation in initialization and elsewhere. A getter takes self; a setter takes self and the value being assigned.

  32. Michael

    There’s an important Python caveat, though: these protections are largely based on convention, not strict privacy controls. A leading underscore signals that an attribute is intended for internal use—roughly, “please don’t touch this.” But Python does not stop someone from accessing or changing _house directly.

  33. Anna

    So properties help make normal use safer and communicate how the class should be used, but they’re not an unbreakable security barrier. The underscore is a convention; programmers are expected to respect it.

  34. Michael

    Classes can also be useful as organized containers for behavior that belongs to a concept, even when we don’t need to create individual objects. That brings us to class methods and class variables.

  35. Anna

    Consider a Sorting Hat that randomly assigns a student to one of four houses. If we model it as an ordinary class with instance methods, we might create multiple hats, even though the fictional example calls for one shared sorting function and one shared list of houses.

  36. Michael

    A class variable belongs to the class itself rather than to one particular object. We can define houses once on the Hat class, then access that shared list from a class method. We mark a class method with @classmethod, and its first parameter is conventionally cls, a reference to the class.

  37. Anna

    Then we can call Hat.sort('Harry') directly, without first making a Hat object. The sort method can choose randomly from cls.houses. The class acts as a container for related data and functionality, even if we don’t instantiate it.

  38. Michael

    That doesn’t mean a class is always necessary. For a small example, a module-level list and function could be perfectly adequate. Classes become especially useful as a program grows and related data and functions multiply; they help keep those concepts organized. Python also has static methods, marked with @staticmethod, though we’re not exploring them in detail here.

  39. Anna

    And the standard types we’ve been using are classes too. Integers, strings, lists, and dictionaries are built-in classes. Creating an integer or string gives us an object of that type, and methods such as string.lower(), string.strip(), and list.append() are methods provided by those classes.

  40. Michael

    We can inspect a value with type(), for example type(50), type('hello'), type([]), or type({}). The output identifies the class—int, str, list, or dict. Built-in class names are often lowercase, while the convention for classes we define ourselves is to capitalize the first letter, as in Student.

  41. Anna

    Another major feature of object-oriented programming is inheritance. It lets one class inherit behavior and attributes from another, which can reduce duplication when the classes have something in common.

  42. Michael

    For example, imagine Wizard as a general class with a name and name validation. Student and Professor can be more specific kinds of Wizard: a student also has a house, and a professor also has a subject. We express that relationship by putting Wizard in parentheses after each subclass name.

  43. Anna

    Student and Professor can inherit Wizard’s shared functionality, but each can also add its own details. Since each subclass has its own __init__, it needs to call the parent’s initializer to set up the shared name. The common pattern is super().__init__(name).

  44. Michael

    Here, super() gives us access to the parent class, and calling its __init__ runs the Wizard initialization. The subclass can then set self.house or self.subject. That way we write the shared name assignment and validation once, instead of copying them into both subclasses.

  45. Anna

    Inheritance can extend through several levels: a class can inherit from a subclass and receive functionality from ancestors further up the hierarchy. A subclass can also override inherited behavior when it needs to work differently. Python can support multiple inheritance as well, though this example uses a simple single-parent hierarchy.

  46. Michael

    Python’s exception types are organized in a hierarchy too. ValueError, for instance, inherits from Exception, which inherits from BaseException. That shared structure lets a program catch a specific error when appropriate, or catch a broader parent type when it needs to handle a group of related errors similarly.

  47. Anna

    The final feature is operator overloading: defining what familiar operators mean for objects of a class. Python already uses plus in different ways—for example, adding numbers, concatenating strings, and combining lists. The meaning depends on the objects involved.

  48. Michael

    We can define our own meaning for plus with the special method __add__. Imagine a Vault class holding numbers of Galleons, Sickles, and Knuts. Its __init__ can store those amounts, with zero as a default, and __str__ can return a readable description of the vault.

  49. Anna

    Without __add__, Python doesn’t know how to combine two Vault objects, so adding them raises a TypeError. But if we define __add__(self, other), Python calls that method when it sees left_vault + right_vault. By convention, self refers to the object on the left and other to the object on the right.

  50. Michael

    Inside __add__, we add the two vaults’ Galleons, Sickles, and Knuts separately, create a new Vault with those totals, and return it. Then Potter’s vault plus Weasley’s vault produces a new combined vault, and the plus expression is much clearer than manually writing each addition at the call site.

  51. Anna

    The method defines the behavior, though it’s up to the programmer to make sure that behavior makes sense. A class could technically receive a different kind of object on the other side of plus, but the method has to handle that type sensibly or an error may result.

  52. Michael

    There are many special methods for operators, including methods for subtraction and comparison operators. Python provides a defined set of operators that can be overloaded; we don’t invent arbitrary new operator symbols.

  53. Anna

    So the big picture is that classes let us define our own data types, objects are individual instances of those types, and methods give those objects behavior. Properties and exceptions can help us validate data; class methods and class variables organize functionality shared at the class level; inheritance shares behavior across related classes; and special methods let objects work naturally with built-in syntax.

  54. Michael

    And none of that means tuples, lists, or dictionaries are obsolete. They’re still useful tools. Object-oriented programming is another tool in the toolkit—particularly valuable when a program grows and we want related data and behavior grouped into clear, reusable structures.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent