Python Tutorial

Python Variable

Python Operators

Python Sequence

Python String

Python Flow Control

Python Functions

Python Class and Object

Python Class Members (properties and methods)

Python Exception Handling

Python Modules

Python File Operations (I/O)

Python class namespace

In Python, a namespace is a mapping between names and their corresponding objects. Each class has its own namespace, which stores its attributes and methods. When you create an instance of a class, the instance has access to its class's namespace and can use the class's attributes and methods. Here's a tutorial on Python class namespaces:

  • Define a class with attributes and methods:
class MyClass:
    x = 10  # Class attribute

    def print_hello(self):
        print("Hello")
  • Understand class namespaces:

The namespace of a class can be accessed using the __dict__ attribute. It contains the class's attributes and methods:

print(MyClass.__dict__)
# Output: {'__module__': '__main__', 'x': 10, 'print_hello': <function MyClass.print_hello at ...>, '__dict__': <attribute '__dict__' of 'MyClass' objects>, '__weakref__': <attribute '__weakref__' of 'MyClass' objects>, '__doc__': None}

In this example, the class namespace contains the x attribute and the print_hello method.

  • Access class attributes:

Class attributes can be accessed using the dot notation:

print(MyClass.x)  # Output: 10
  • Create an instance of the class:

When you create an instance of a class, the instance has its own namespace that initially contains only the instance-specific attributes:

my_instance = MyClass()
print(my_instance.__dict__)  # Output: {}
  • Access class attributes from an instance:

Instance objects can access their class's namespace. When you try to access an attribute on an instance, Python first looks in the instance's namespace. If the attribute is not found, Python looks in the class's namespace:

print(my_instance.x)  # Output: 10
  • Add attributes to the instance:

When you add attributes to an instance, they are stored in the instance's namespace:

my_instance.y = 20
print(my_instance.__dict__)  # Output: {'y': 20}
  • Override class attributes in an instance:

If you add an attribute to an instance with the same name as a class attribute, the instance attribute will override the class attribute in the instance's namespace:

my_instance.x = 30
print(my_instance.x)  # Output: 30
print(MyClass.x)  # Output: 10

In this example, the x attribute in the instance's namespace overrides the x attribute in the class's namespace, but only for the my_instance object. The class attribute remains unchanged.

This tutorial covered the basics of Python class namespaces, how to access them, and how instances can use and override the attributes and methods from their class's namespace. Understanding namespaces is essential for working with classes and instances, as it helps you predict the behavior of your objects and avoid potential issues.

  1. Accessing and modifying class attributes in Python:

    • Description: Class attributes can be accessed using the class name or an instance of the class. They can be modified at the class level, affecting all instances.
    • Code:
      class MyClass:
          class_attribute = 42
      
      print(MyClass.class_attribute)  # Output: 42
      
      # Modifying class attribute
      MyClass.class_attribute = 55
      print(MyClass.class_attribute)  # Output: 55
      
  2. Class-level variables and methods in Python namespace:

    • Description: Class-level variables and methods are stored in the class namespace, accessible using the class name or instances of the class.
    • Code:
      class MyClass:
          class_variable = 42
      
          @classmethod
          def class_method(cls):
              print("This is a class method")
      
      print(MyClass.class_variable)  # Output: 42
      MyClass.class_method()         # Output: This is a class method
      
  3. Encapsulation and privacy in Python class namespace:

    • Description: Encapsulation in Python is achieved by using single or double underscores as name prefixes, indicating the level of privacy. However, Python follows the principle of "we are all consenting adults here."
    • Code:
      class MyClass:
          _protected_variable = "I'm protected"
          __private_variable = "I'm private"
      
      print(MyClass._protected_variable)  # Output: I'm protected
      # Name mangling for private variable
      print(MyClass._MyClass__private_variable)  # Output: I'm private
      
  4. Class instance namespace vs class namespace in Python:

    • Description: The class instance namespace is unique for each instance and includes both instance-specific and class-level attributes. The class namespace is shared among all instances.
    • Code:
      class MyClass:
          class_variable = 42
      
          def __init__(self, instance_variable):
              self.instance_variable = instance_variable
      
      obj1 = MyClass(10)
      obj2 = MyClass(20)
      
      print(obj1.class_variable)         # Output: 42
      print(obj1.instance_variable)      # Output: 10
      print(obj2.class_variable)         # Output: 42
      print(obj2.instance_variable)      # Output: 20
      
  5. Dynamic modification of class namespace in Python:

    • Description: The class namespace can be dynamically modified by adding, modifying, or deleting attributes during runtime.
    • Code:
      class MyClass:
          pass
      
      # Adding a class attribute dynamically
      MyClass.new_attribute = "I'm new"
      print(MyClass.new_attribute)  # Output: I'm new
      
      # Modifying the class attribute dynamically
      MyClass.new_attribute = "I'm modified"
      print(MyClass.new_attribute)  # Output: I'm modified
      
      # Deleting the class attribute dynamically
      del MyClass.new_attribute