xSKILLby Infirals
Register

Python for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Classes

Objects and errors6 min readLesson 1 of 3

A class bundles data with the functions that act on it.

python
class Student:
    def __init__(self, name, score):
        self.name = name
        self.score = score

    def passed(self):
        return self.score >= 60

ada = Student("Ada", 92)
ada.passed()          # True

__init__ sets up a new instance; self is that instance. Methods are called on the instance, so self is passed for you.

Special methods hook into the language itself:

python
def __repr__(self):
    return f"Student({self.name!r}, {self.score})"

__repr__ is the debugging view and what you see in the REPL. Write it for every class you plan to print.

Prefer a plain function or a dictionary until the data and behaviour really belong together.

Quiz

Check: Python classes

Four questions on __init__, self, methods and the debugging representation of an object.

4 questions

Question 1 of 4

0/4 answered

__init__ is the method that:

Answer all you can, then submit.