CodeGym /Courses /Python SELF EN /Utility Methods and Fields

Utility Methods and Fields

Python SELF EN
Level 15 , Lesson 5
Available

5.1 Access Levels

You might have noticed the weird constructor name __init__? You'll run into this kind of thing pretty often in the future.

In Python, there are different access levels for class attributes and methods that help you control visibility and data protection. The main mechanisms for managing access include using one or two underscores (_ and __) before an attribute or method name.

Using Conventions

Single Underscore _ is used for attributes and methods that shouldn't be used outside of a class or module. It's not forbidden, but it's a convention that should be followed for better code readability and maintenance.

Double Underscore __ is used for attributes and methods that should be truly private and protected from accidental or deliberate external access. The name mangling mechanism makes them less accessible but still available via special names.

Public (public) Fields and Methods

Public attributes and methods are accessible from anywhere in the code. In Python, by default, all attributes and methods are public unless their names start with an underscore.


class MyClass:
    def __init__(self):
        self.public_attribute = "I am public"
        
    def public_method(self):
        return "This is a public method"
        

obj = MyClass()
print(obj.public_attribute)  # Accessible
print(obj.public_method())  # Accessible

Access levels in Python implement encapsulation, specifically through non-public fields and methods.

5.2 Non-Public Fields and Methods

Protected (protected) Fields and Methods

Protected attributes and methods are marked by a single underscore _ before the name and are intended for internal use within a class and its subclasses. This is a convention that tells programmers the data is not meant to be used outside the class.


class MyClass:
    def __init__(self):
        self._protected_attribute = "I am protected"
        
    def _protected_method(self):
        return "This is a protected method"
        

obj = MyClass()
print(obj._protected_attribute)  # Accessible but not recommended
print(obj._protected_method())  # Accessible but not recommended

Private (private) Fields and Methods

In Python, private attributes and methods are indicated by two underscores __ before the name. These attributes and methods are meant for use exclusively within the class, and their main purpose is to hide internal implementation and protect data from accidental changes or external use.

To prevent direct access to such attributes and methods from external code, Python uses a special mechanism known as name mangling. This mechanism automatically alters the names of private attributes by adding a prefix consisting of the class name. Thus, the private attribute __private_attribute in the class MyClass will be transformed into the internal name _MyClass__private_attribute.

This allows data to be protected from unintentional access while maintaining the ability to work with it within the class. However, it's important to remember that the "name mangling" mechanism is not absolute protection—a savvy programmer can access these data using the altered name.

Let's see how this works in practice:


class MyClass:
    def __init__(self):
        self.__private_attribute = "I am private"
        
    def __private_method(self):
        return "This is a private method"
        
    def access_private_method(self):
        return self.__private_method()
         

obj = MyClass()
# print(obj.__private_attribute)  # Error, not directly accessible
# print(obj.__private_method())  # Error, not directly accessible
print(obj.access_private_method())  # Accessible through a public class method

As seen in the example, direct access to private attributes or methods throws an error. But Python retains the ability to access them through the altered name. For instance, you can access a private attribute using the "mangled" name, as shown below:


class MyClass:
    def __init__(self):
        self.__private_attribute = "I am private"
   
obj = MyClass()
print(obj._MyClass__private_attribute)  # Outputs: I am private

While accessing through the "mangled" name is possible, it should be avoided, as it breaks encapsulation principles and can lead to code instability.

To see how Python alters attribute names, you can use the built-in dir() function, which lists all available attributes and methods of an object:


class MyClass:
    def __init__(self):
        self.__private_attribute = "I am private"
   
obj = MyClass()
print(dir(obj))  # Displays all attributes and methods of the object, including "mangled" names

As a result of using the dir() function, you'll see a list of all the object's attributes and methods, including _MyClass__private_attribute, confirming the "name mangling" mechanism.

5.3 Automatic Method Calling

There was an interesting aspect when working with constructors that you might have noticed. The __init__ method was called automatically.

Actually, there are quite a few of these situations, as well as methods for these cases. Examples:

Method __str__

If your object has the __str__ method, it will be called automatically when you try to convert your object to a string, for example, when using the print() and str() functions.


class Cat:
    def __init__(self, name, age):
        self.name = name
        self.age = age
            
    def __str__(self):
        return f"{self.name} is {self.age} years old"
            

cat = Cat("Barsik", 5)
print(cat)  # Outputs: Barsik is 5 years old

Method __len__

If your object has the __len__ method, it will be called automatically when you try to determine the "length" of your object—used by the len() function. Example:


class MyList:
    def __init__(self, items):
        self.items = items
        
    def __len__(self):
        return len(self.items)
        
        
my_list = MyList([1, 2, 3])
print(len(my_list))  # Outputs: 3

You're going to encounter many more of these "magic methods" in your programming journey, and working with them is a joy. So, get ready :)

2
Task
Python SELF EN, level 15, lesson 5
Locked
Defend yourself.
Defend yourself.
2
Task
Python SELF EN, level 15, lesson 5
Locked
Library.
Library.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION