Embedding Versus Inheritance
Lesson 39 of 48 in Coddy's Python for C Developers course.
C struct embedding stores a base-shaped member but does not itself create language-level inheritance or virtual dispatch. Python declares a subclass in parentheses and searches methods along the method resolution order. If a subclass defines __init__, it must explicitly call base initialization when that state is needed. super refers to the next implementation in that resolution order; in this single-inheritance example that is Pass. The overridden cost can extend the base behavior without duplicating its current-price lookup.
C: complete example.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
struct Pass { int price; };
struct Discount { struct Pass base; int discount; };
int main(void) {
struct Discount d = {{10}, 3};
printf("%d\n", d.base.price - d.discount);
return 0;
}Python: complete example.py
class Pass:
def __init__(self, price):
self.price = price
def cost(self):
return self.price
class Discount(Pass):
def __init__(self, price, discount):
super().__init__(price)
self.discount = discount
def cost(self):
return super().cost() - self.discount
print(Discount(10, 3).cost())Watch the difference
Do not treat super as a C pointer cast or as an independent copy of the base object. Base and subclass methods operate on the same instance. Keep composition for replaceable collaborators; use inheritance when the subclass relationship is intentional.
Your code goes in pass_model.py, discount_pass.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.
Challenge
BeginnerImplement Pass(label,price), storing attributes and returning current price from cost(). Implement DiscountPass(label,price,discount) as a subclass, initialize the base via super().__init__, and return max(0, base cost minus discount) from its override. Inputs are label and nonnegative price/discount. The driver prints regular and discounted label/cost pairs, changes the discounted price by 10, then prints its new cost; it also checks subclassing.
Implement the named definitions in the editable modules without input or printing. The driver owns input/output and may call the APIs again on fresh data without producing extra output.
C struct embedding does not provide Python inheritance. Explicitly initialize base state with super here.
Your code goes in pass_model.py, discount_pass.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.
Try it yourself
from pass_model import Pass
from discount_pass import DiscountPass
assert issubclass(DiscountPass, Pass), "Required subclass relationship missing"
label = input()
price, discount = int(input()), int(input())
a, b = Pass(label, price), DiscountPass(label, price, discount)
print(a.label, a.cost())
print(b.label, b.cost())
b.price += 10
print(b.cost())
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for C Developers
1From C Programs to Python
Run Python Without mainPrinting Without Format CodesNames Versus Typed StorageDivision and Integer LimitsSuites Instead of BracesRecap: A Python Receipt4Iteration and Transformations
Iteration Without PointersIndexes Without Pointer MathSentinels and Loop ControlComprehensions and SortingRecap: Stable Ranking2Values and Truth Tests
Absence Is Not a Null PointerContent Versus Object IdentityTruth Tests and OperandsConditional Value SelectionRecap: Missing or Eligible5Functions and Callbacks
Functions and Object ArgumentsDefaults and Named ArgumentsVarargs Without va_listCallbacks and Captured NamesRecap: Pricing Functions8Composition and Inheritance
Callbacks to CompositionEmbedding Versus InheritanceBehavior Without VtablesEquality and Data ClassesRecap: Pluggable Channels3Containers and Aliasing
Lists Versus C ArraysTuples and Struct ValuesMappings and Lookup LoopsPointers, Copies, and AliasesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputError Codes Versus ExceptionsImports Are Not IncludesAnnotations Versus C TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler