What are different attributes in Python?

Home » Python » What are different attributes in Python?

Table of Contents

Introduction to different attributes in Python

Attributes in Python of a class or variable can have different levels of visibility and accessibility.These levels are controlled using the globalprotected, and private naming conventions.

These conventions determine how variables or methods can be accessed from outside the class, module, or function.

Python employs conventions and syntactic rules to indicate how attributes should be accessed, though it doesn’t enforce strict access control mechanisms.

Here’s a detailed explanation of each:

1. Global Attributes:

  • Global attributes are variables or objects that are defined outside of any class, method, or function, usually at the top level of a script or module.
  • They can be accessed by any function or method within the same module or even from other modules (if properly imported).

Example of Global Attributes:


# Global variable
x = 10

def print_x():
    print(x)  # Accessing the global variable

print_x()  # Output: 10

Access: Global variables are accessible by all parts of the code, as long as they are within the same scope or module.

2. Protected Attributes:

  • The only use of protected attributes when we want it to use within the class or its subclasses.
  • These variables are still accessible from outside the class, but the convention is to treat them as internal and not to access them directly.
  • In Python, the protected attribute is indicated by a single underscore (_) before the attribute name.
  • Python wants the developers by the use of a single underscore. It is for internal use only and shoudn’t access it from outside of the class.It doesn’t actually restrict access.

Example of Protected Attributes:


class Animal:
    def __init__(self, name):
        self._name = name  # Protected attribute
    
    def display(self):
        print(f"Animal's name: {self._name}")

class Dog(Animal):
    def display(self):
        print(f"Dog's name: {self._name}")  # Accessing protected attribute from subclass

dog = Dog("Buddy")
dog.display()  # Output: Dog's name: Buddy

Access: You can still access _name outside the class, but it is intended to be protected.

3. Private Attributes:

  • We use private attributes only when we want it to use with the class which we have defined.
  • In Python, private attributes are indicated by a double underscore (__) before the attribute name.
  • When there’s a use of double underscores, we know that there name mangling, which means that this attribute name is going to change internally which makes it less accessible from outside of the class.

Example of Private Attributes:


class Car:
    def __init__(self, make, model):
        self.__make = make  # Private attribute
        self.__model = model  # Private attribute

    def display_info(self):
        print(f"Car make: {self.__make}, Model: {self.__model}")

car = Car("Toyota", "Corolla")
car.display_info()  # Output: Car make: Toyota, Model: Corolla

# Trying to access private attribute outside the class
# This will raise an AttributeError
# print(car.__make)  # Uncommenting this will result in an error

Access: Attempting to access __make or __model outside the class will raise an error. However, Python does name mangling on the attribute which allows it to be accesses by the mangled name also.

Name Mangling: When you define an attribute with a double underscore (__), Python internally changes the name of the attribute to _ClassName__attributeName. This helps avoid accidental access or modification of private attributes but does not provide true access control like in other languages.

When to Use Each:

  • Global Attributes: We use them when we need a variable or object. This variable can be available across multiple functions or classes with the same module.
  • Protected Attributes: We use them when there’s a need to indicate an attribute which should only be available within the class or its subclasses. But not by any external code.
  • Private Attributes: For use within a class only. Name mangling helps avoid accidental external access.

Conclusion of different attributes in Python:

In Python, attributes can be globalprotected, or private based on the naming convention and the level of access control you want to implement.

Python doesn’t have strict enforcements like languages Java or C++. But we use these conventions to best use attributes.


Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *