CS 112 › Lesson 1 of 10

Classes, Objects & Constructors

Lesson 1 · OKSTEM College · Associate of Science in Computer Science

Classes, Objects & Constructors

A class is a blueprint; an object is a concrete instance created from that blueprint. Python's __init__ method is the constructor — it runs automatically when a new object is created.

class Student: """A student at OKSTEM College.""" def __init__(self, name: str, gpa: float): self.name = name # instance variable self.gpa = gpa self.courses: list = [] def enroll(self, course: str) -> None: self.courses.append(course) def __repr__(self) -> str: return f"Student({'{'}self.name!r{'}'}, gpa={'{'}self.gpa{'}'})" # Usage alice = Student("Alice", 3.9) alice.enroll("CS 201") print(alice.courses) # ['CS 201'] print(repr(alice)) # Student('Alice', gpa=3.9)

Every method's first parameter is self — a reference to the instance. Python passes it automatically; you never pass it explicitly when calling a method.

Knowledge Check

The __init__ method is called

'self' in a Python method refers to

Instance variables are set on

Which method controls how an object is displayed with repr()?

A class is best described as

Next →