Understanding Python’s Duck Typing and Monkey Patching with Real Code
This article explains Python’s dynamic features—duck typing and monkey patching—through clear analogies and practical code examples, demonstrating how objects are identified by behavior rather than type and how classes or modules can be modified at runtime without altering original source code.
1. Duck Typing
Duck typing means that an object's suitability is determined by the presence of required methods and attributes rather than its explicit type.
Python is dynamically typed, so there is no strict type checking. If an object implements the same interface as a duck, it can be used wherever a duck is expected.
# Duck class
class Duck:
def __init__(self, name):
self.name = name
def swim(self):
print("A duck named " + self.name + " is swimming...")
def call(self):
print("gay...gay...gay...")
# Goose class (has same methods as Duck)
class Goose:
def __init__(self, name):
self.name = name
def swim(self):
print("A goose named " + self.name + " is swimming...")
def call(self):
print("goo...goo...goo...")
# Function that expects a Duck‑like object
def duckshow(duck):
duck.swim()
duck.call()
yaya = Duck("yaya")
ee = Goose("ee")
duckshow(yaya)
duckshow(ee)2. Monkey Patching
Monkey patching refers to modifying or extending a class or module from outside its original definition, which can be useful but may break encapsulation.
# Define a Dog class
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def sleep(self):
print("Zzz...Zzz..Zzz...")
# Add new methods to Dog from outside
def speak(self):
print("I think myself a hero and very handsome!")
Dog.speak = speak
Dog.home = "Earth"
snoopy = Dog("snoopy", 3)
snoopy.sleep()
snoopy.speak()
print(snoopy.home)Monkey patching can also be applied to library classes, such as adding a concise memory‑display method to pandas DataFrames.
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(1, 10, size=(5,5)),
columns=list("abcde"))
def memory(self):
mem = self.__sizeof__()
if mem < 1024:
return f"{mem} B"
elif mem < 1024*1024:
return f"{mem/1024:.0f} KB"
elif mem < 1024**3:
return f"{mem/1024**2:.0f} MB"
else:
return f"{mem/1024**3:.0f} GB"
pd.DataFrame.memory = memory
print(df.memory())These examples illustrate how Python’s duck typing and monkey patching enable flexible, runtime behavior modifications.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
