Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

An instance attribute is a variable bound to a specific, instantiated object of a class rather than the class itself. Each object maintains its own independent copy of the attribute, meaning state modifications to an instance attribute on one object do not affect other objects of the same class. Instance attributes are typically defined and initialized within the class constructor (the __init__ method) using the self reference, which represents the current object instance in memory.
class Connection:
    def __init__(self, host, port):
        self.host = host  # Instance attribute
        self.port = port  # Instance attribute

Underlying Mechanism

Python stores instance attributes in a dedicated namespace dictionary for each object, accessible via the __dict__ magic attribute. When an attribute is accessed via dot notation (object.attribute), Python resolves it by first checking the instance’s __dict__. If the attribute is not found there, the interpreter falls back to checking the class __dict__.
conn1 = Connection("127.0.0.1", 8080)
conn2 = Connection("192.168.1.1", 9000)


# Each instance maintains an independent namespace dictionary
print(conn1.__dict__)  # Output: {'host': '127.0.0.1', 'port': 8080}
print(conn2.__dict__)  # Output: {'host': '192.168.1.1', 'port': 9000}

Dynamic Assignment and Deletion

Because Python objects are mutable by default, instance attributes are not strictly confined to the __init__ method. They can be dynamically bound to or unbound from an instance at runtime using standard dot notation or the built-in setattr() and delattr() functions. Modifying the attributes dynamically directly mutates the instance’s __dict__.

# Dynamic assignment
conn1.timeout = 30
setattr(conn1, 'protocol', 'TCP')

print(conn1.__dict__) 

# Output: {'host': '127.0.0.1', 'port': 8080, 'timeout': 30, 'protocol': 'TCP'}


# Dynamic deletion
del conn1.port
delattr(conn1, 'host')

print(conn1.__dict__) 

# Output: {'timeout': 30, 'protocol': 'TCP'}

Memory Optimization (__slots__)

By default, the use of __dict__ incurs a memory overhead. If a class defines a __slots__ iterable, Python suppresses the creation of the __dict__ for instances of that class, allocating space only for a fixed set of instance attributes. This prevents the dynamic creation of new instance attributes outside of those explicitly declared.
class OptimizedConnection:
    __slots__ = ['host', 'port']

    def __init__(self, host, port):
        self.host = host
        self.port = port

opt_conn = OptimizedConnection("10.0.0.1", 443)

# opt_conn.timeout = 30  # Raises AttributeError: 'OptimizedConnection' object has no attribute 'timeout'
Master Python with Deep Grasping Methodology!Learn More