Lesson 29 of 55
10 mins readPython Inner & Outer Constructors
In Plain English
Constructors instantiate structs. Inner constructors have access to the special new() function to enforce invariants; outer constructors provide convenient alternative signatures.
Deep Dive: How It Works
Default Constructor: Automatically generated if no inner constructor is defined.
Inner Constructor: Defined inside the struct body. Replaces the default constructor to validate arguments before calling new(args...).
Outer Constructor: Defined outside the struct to provide convenience overloads (e.g. constructing from a single argument).
Core Rules to Remember

Invariant Enforcement with new(): Prevent invalid objects from being constructed at runtime.

Outer Convenience Methods: Provide default parameters or format conversions seamlessly.
Live Interactive Example
Hit Run Code to see it liveOrdered Interval with Inner Constructor
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Output Console
Click "Run Code" to view the rendered output.
How it works: new() initializes the struct fields safely after the validation check passes.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Validate Positive Radius
Define `struct Circle radius::Float64` with an inner constructor checking `r > 0`.
Create `c = Circle(3.5)` and print `"Radius: $(c.radius)"`.
1
2
3
4
5
6
7
8
9
10
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.