jypi
  • Explore
ChatWays to LearnMind mapAbout

jypi

  • About Us
  • Our Mission
  • Team
  • Careers

Resources

  • Ways to Learn
  • Mind map
  • Blog
  • Help Center
  • Community Guidelines
  • Contributor Guide

Legal

  • Terms of Service
  • Privacy Policy
  • Cookie Policy
  • Content Policy

Connect

  • Twitter
  • Discord
  • Instagram
  • Contact Us
jypi

© 2026 jypi. All rights reserved.

CS50 - Introduction to Computer Science
Chapters

1Computational Thinking and Foundations

2C Language Basics

3Arrays, Strings, and Algorithmic Basics

4Algorithm Efficiency and Recursion

5Memory, Pointers, and File I/O

6Core Data Structures in C

7Python Fundamentals

8Object-Oriented and Advanced Python

Classes and ObjectsMethods and AttributesConstructors and __init__Inheritance and CompositionPolymorphism and Duck TypingSpecial Methods and __str__Iterators and GeneratorsDecorators and functoolsContext ManagersTyping and Type HintsDataclassesStandard Library TourUnit Testing with unittestLogging and DebuggingPackaging and Distribution

9Relational Databases and SQL

10Web Foundations: HTML, CSS, and JavaScript

11Servers and Flask Web Applications

12Cybersecurity and Privacy Essentials

13Software Engineering Practices

14Version Control and Collaboration

15Capstone: Designing, Building, and Presenting

Courses/CS50 - Introduction to Computer Science/Object-Oriented and Advanced Python

Object-Oriented and Advanced Python

12908 views

Structure larger programs with classes, iterators, decorators, and typing.

Content

3 of 15

Constructors and __init__

Python Constructors and __init__ Explained (CS50 Guide)
4653 views
beginner
python
object-oriented
humorous
gpt-5-mini
4653 views

Versions:

Python Constructors and __init__ Explained (CS50 Guide)

Watch & Learn

AI-discovered learning video

Sign in to watch the learning video for this topic.

Sign inSign up free

Start learning for free

Sign up to save progress, unlock study materials, and track your learning.

  • Bookmark content and pick up later
  • AI-generated study materials
  • Flashcards, timelines, and more
  • Progress tracking and certificates

Free to join · No credit card required

Constructors and init in Python — The CS50 Way

You already know classes and objects, and you've been messing with methods and attributes. Now let's give our objects a personality from day one.


Why this matters (quick refresher)

You learned in the previous sections how to define a class and call methods on objects. But how do you make sure every new object starts in a valid, ready-to-go state? That's the constructor's job. In Python, that job is usually done by the special method init.

Think of classes like blueprints and init like the factory worker who bolts the engine in, fills the oil, and hands you a fully assembled car. Without init, you get a shell and then have to remember to attach the wheels later — messy.


What is init?

  • init is the initializer (often called the constructor) for an instance.
  • It runs right after Python creates a new object, letting you set up attributes and enforce invariants.
  • Its signature always starts with self: def __init__(self, ...).

Micro explanation: init does not create the object. Python first allocates the object, then calls init to initialize it. If you want to mess with allocation itself, meet new (advanced, rarely needed).


Basic example (the warm-up)

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

s = Student('Ava', 2)
print(s.name)  # Ava
print(s.year)  # 2
  • self.name and self.year are instance attributes created during construction.
  • After s = Student('Ava', 2), s is ready to use: attributes exist and are meaningful.

Why not set attributes later?

Because forgetting to set them causes AttributeError at runtime. Constructors centralize setup and make code safer and more readable.


Common constructor patterns and pitfalls

1) Default arguments

class Counter:
    def __init__(self, start=0):
        self.count = start

You can provide defaults so callers get sensible behavior without passing every argument.

2) Avoid mutable default arguments

Bad:

class Bag:
    def __init__(self, items=[]):
        self.items = items

Good:

class Bag:
    def __init__(self, items=None):
        if items is None:
            items = []
        self.items = items

Why: A mutable default gets shared across all instances.

3) Validation inside init

class Person:
    def __init__(self, age):
        if age < 0:
            raise ValueError('age must be >= 0')
        self.age = age

Constructors are an excellent place to validate input early.


Advanced: multiple constructors and @classmethod

Sometimes you want alternate ways to create objects, e.g., from a dict or a JSON string.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    @classmethod
    def from_tuple(cls, t):
        return cls(t[0], t[1])

p = Point.from_tuple((3, 4))
  • from_tuple is not a special method — it's just a classmethod that returns a new instance. Very handy for named constructors.

Inheritance and super().init

If your class inherits from a parent that needs setup, call super().__init__().

class Animal:
    def __init__(self, species):
        self.species = species

class Dog(Animal):
    def __init__(self, name):
        super().__init__('Canis familiaris')
        self.name = name

d = Dog('Rex')
print(d.species, d.name)  # Canis familiaris Rex
  • super().__init__() ensures the base class gets initialized too.
  • Forgetting to call it can leave base attributes uninitialized.

init vs new (short, CS50-friendly)

  • __new__(cls, ...) — actually creates and returns the new instance (rarely overridden).
  • __init__(self, ...) — initializes the instance returned by __new__ and must return None.

You will almost always use init. Override new only for advanced use-cases like immutable singletons or custom memory allocation.


Comparison table (quick scan)

Role Typical method When used
Create object new Very rarely (advanced)
Initialize object init Almost always
Alternative constructors @classmethod, factory functions When multiple creation APIs are needed

Little freakouts and neat tricks

  • Want optional flexibility? Use *args/**kwargs to accept variable input and pass to super() or other factories.
  • Need immutability? Initialize attributes and avoid setters; for full immutability, explore @dataclass(frozen=True) later.
  • Want readable error messages? Validate early in init so bugs surface at object creation, not later.

Quick checklist when writing an init

  1. Give every instance a valid, consistent state.
  2. Avoid mutable defaults.
  3. Validate critical inputs (raise ValueError/TypeError early).
  4. Call super().__init__() when inheriting.
  5. Keep init focused — heavy logic belongs in other methods or helper functions.

Final recap — what to remember

  • init sets up instances. It runs after the object is created so attributes exist immediately.
  • Use init to centralize state and validation. This makes your objects reliable and bug-resistant.
  • For alternate ways to create objects, prefer @classmethods (named constructors) rather than overloading init with many different argument shapes.

"This is the moment where the concept finally clicks." — When you see a class that always sets its attributes in init, you’ll stop asking whether an object is 'ready' and start trusting it.


Key takeaways:

  • init = initializer; keep it clear and defensive.
  • Avoid mutable defaults.
  • Use classmethods for alternate constructors and super() for inheritance.

Go try it: refactor an earlier class you wrote (from Methods and Attributes) to use a proper init. Your future self will send you a thank-you emoji.

Flashcards
Mind Map
Speed Challenge

Comments (0)

Please sign in to leave a comment.

No comments yet. Be the first to comment!

Ready to practice?

Sign up now to study with flashcards, practice questions, and more — and track your progress on this topic.

Study with flashcards, timelines, and more
Earn certificates for completed courses
Bookmark content for later reference
Track your progress across all topics