Embedding Is Not Inheritance
Lesson 39 of 48 in Coddy's Python for Go Developers course.
Go embeds a field to promote selectors; it does not have class inheritance or make the outer struct assignable to the embedded type. Python names a base class in parentheses and supports inherited methods and overriding. If a subclass defines __init__, it must call base initialization when needed. super() follows Python method resolution order, which is more general than a textual call to a named parent. Composition remains useful when only collaboration is needed.
Go
Go excerpt: declarations above main, statements inside main. Imports: fmt. The verification bundle contains the complete program.
type Pass struct { Price int }
func (p Pass) Cost() int { return p.Price }
type DiscountPass struct { Pass; Discount int }
func (d DiscountPass) Cost() int { n := d.Pass.Cost()-d.Discount; if n < 0 { return 0 }; return n }
// Inside main:
d := DiscountPass{Pass: Pass{Price: 100}, Discount: 15}
fmt.Println(d.Cost())
d.Price = 120
fmt.Println(d.Cost())Python
class Pass:
def __init__(self, price):
self.price = price
def cost(self):
return self.price
class DiscountPass(Pass):
def __init__(self, price, discount):
super().__init__(price)
self.discount = discount
def cost(self):
return max(0, super().cost() - self.discount)
d = DiscountPass(100, 15)
print(d.cost())
d.price = 120
print(d.cost())Porting trap
Go embedded methods execute with their declared receiver; they do not gain Python-style virtual dispatch through the outer value. Do not treat promoted Go methods and Python overriding as interchangeable models.
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. Go embedding is not inheritance; this Python subclass must explicitly call the base initializer.
Editable files: pass_model.py, discount_pass.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.
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.
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 Go Developers
1From Go to Python
Run Your First Python ProgramPrinting, Quotes, and CommentsBindings Beyond Go TypesDivision and Growing IntegersIndentation and ScopeRecap: A Python Receipt4Iteration and Transformations
range and Value IterationIndexes and Map EntriesSentinels Without Truth TrapsComprehensions and Stable SortRecap: Stable Ranking2Values, Absence, and Branches
None, nil, and Zero ValuesEquality Is Not IdentityTruth Tests Beyond boolBranches and Value SelectionRecap: Missing or Eligible5Functions and Call Contracts
Functions and Tuple ReturnsDefaults and Named ArgumentsVariadics and Keyword OptionsClosures and Callable ValuesRecap: Pricing Functions8Interfaces and Object Design
Interface Fields and CallsEmbedding Is Not InheritanceInterfaces and Duck TypingStructs and Data ClassesRecap: Pluggable Channels3Slices, Maps, and Sharing
Slices Versus Python ListsMultiple Values and TuplesGo Maps and Python dictsSets and Shallow CopiesRecap: Inventory Collections6Errors, Modules, and Hints
Text and Exact OutputErrors Versus ExceptionsPackages and Module ExecutionHints Versus Static TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler