Unlock Python’s Hidden Attribute System: __dict__, property, and __getattr__ Explained
This article explains how Python stores object attributes in layered __dict__ structures, distinguishes class and instance attributes, demonstrates attribute lookup, shows how to modify attributes directly or via property, and introduces dynamic attribute creation using __getattr__ and related special methods.
Python treats everything as an object, and each object can have multiple attributes; Python provides a unified system for managing attributes.
Attributes may come from the class definition (class attributes) or be defined on the instance itself (object attributes). All attributes are stored in the object's __dict__, which is a dictionary mapping attribute names to their values.
Consider the following classes and instance:
class bird(object):
feather = True
class chicken(bird):
fly = False
def __init__(self, age):
self.age = age
summer = chicken(2)
print(bird.__dict__)
print(chicken.__dict__)
print(summer.__dict__)The output shows that bird has the attribute feather, chicken adds fly and __init__, and the instance summer stores age. Some attributes like __doc__ are automatically created by Python. All classes ultimately inherit from object.
Python resolves attribute access by searching the instance’s __dict__ first, then moving up the inheritance chain (class, parent class, …) until the attribute is found. If the same attribute exists at multiple levels, the one encountered first (the lowest level) is used.
Attributes can be modified directly or via the __dict__ mapping:
summer.__dict__['age'] = 3
print(summer.__dict__['age'])
summer.age = 5
print(summer.age)When only the instance is known, its class can be obtained with summer.__class__, and the parent class with summer.__class__.__base__.
Properties (特性)
Properties allow attributes to be computed dynamically. For example, we can add an adult property to chicken that returns True when age > 1:
class chicken(bird):
fly = False
def __init__(self, age):
self.age = age
def getAdult(self):
if self.age > 1.0:
return True
else:
return False
adult = property(getAdult)
summer = chicken(2)
print(summer.adult)
summer.age = 0.5
print(summer.adult)The built‑in property() can accept up to four arguments: getter, setter, deleter, and a docstring.
Another example shows a property with all four methods:
class num(object):
def __init__(self, value):
self.value = value
def getNeg(self):
return -self.value
def setNeg(self, value):
self.value = -value
def delNeg(self):
print("value also deleted")
del self.value
neg = property(getNeg, setNeg, delNeg, "I'm negative")
x = num(1.1)
print(x.neg)
x.neg = -22
print(x.value)
print(num.neg.__doc__)
del x.negDynamic attribute creation with __getattr__
The special method __getattr__(self, name) is called when normal lookup fails, allowing on‑the‑fly generation of attributes:
class chicken(bird):
fly = False
def __init__(self, age):
self.age = age
def __getattr__(self, name):
if name == 'adult':
return self.age > 1.0
else:
raise AttributeError(name)
summer = chicken(2)
print(summer.adult)
summer.age = 0.5
print(summer.adult)Other special methods such as __getattribute__ (called for every attribute access), __setattr__, and __delattr__ can be used to control attribute reading, writing, and deletion more broadly.
Summary
Attributes are stored in layered __dict__ structures.
Each layer’s __dict__ holds only the attributes introduced at that level.
Subclass instances inherit attributes without duplicating parent data.
Properties and __getattr__ provide powerful ways to manage and generate attributes dynamically.
Understanding Python’s dynamic attribute mechanisms helps write cleaner, more maintainable code.
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.
