December 2018
Beginner to intermediate
796 pages
19h 54m
English
When you search for an attribute in an object, if it is not found, Python keeps searching in the class that was used to create that object (and keeps searching until it's either found or the end of the inheritance chain is reached). This leads to an interesting shadowing behavior. Let's look at another example:
# oop/class.attribute.shadowing.pyclass Point: x = 10 y = 7p = Point()print(p.x) # 10 (from class attribute)print(p.y) # 7 (from class attribute)p.x = 12 # p gets its own `x` attributeprint(p.x) # 12 (now found on the instance)print(Point.x) # 10 (class attribute still the same)del p.x # we delete instance attributeprint(p.x) # 10 (now search has to go again to find class attr)p.z = 3 # let's make it a 3D point ...Read now
Unlock full access