Day #62 - Access Modifiers in Python

Day #62 - Access Modifiers in Python

ยท

5 min read

Introduction

Welcome to my 62nd blog post on the Python journey. On day 62, I learned about access modifier and their types in python. I learned about public, private and protected access modifiers in python. Let's dive into more details and understand these concepts.

So let's get started......

Access Specifiers/Modifiers

In Python, while implementing the concept of inheritance we can limit the access of class variables and methods outside of class. Here we make use of access specifiers or access modifiers in Python Programming.

Types of access specifiers

  1. Public access modifier

  2. Private access modifier

  3. Protected access modifier

Public Access Specifier

All the variables and methods in Python are by default public. Any instance variable in a class followed by the โ€˜selfโ€™ keyword ie. self.var_name can be publicly accessed from anywhere in the code.

Example -

class Student:
    # constructor is defined
    def __init__(self, age, name):
        self.age = age               # public variable
        self.name = name             # public variable

obj = Student(18,"Ram")
print(obj.age)
print(obj.name)

Private Access Modifier

  • Private variables or methods of a class are those members that are only accessible from inside the class.

  • Private members cannot be outside of class.

  • In Python, there is no strict concept of "private" access modifiers like in some other programming languages. However, a convention has been established to indicate that a variable or method should be considered private by prefixing its name with a double underscore (__).

  • This method of prefixing is known as a "weak internal use indicator" and it is just a convention and not a strict rule.

  • Code outside the class can still access these "private" variables and methods, but it is generally understood that they should not be accessed or modified.

  • Private members cannot be accessed or inherited outside of class. If we try to access these private members it shows error.

Example -

class Student:
    def __init__(self, age, name):
        self.__age = age      # An indication of private variable

        def __funName(self):  # An indication of private function
            self.y = 34
            print(self.y)

class Subject(Student):
    pass

obj = Student(21,"Harry")
obj1 = Subject

# calling by object of class Student
print(obj.__age)
print(obj.__funName())

# calling by object  of class Subject
print(obj1.__age)
print(obj1.__funName())

Concept of 'name mangling'

  • It is a technique that is used to protect class-private and superclass-private attributes from being accidentally overwritten by subclasses.

  • Names of class-private and superclass-private attributes are transformed by the addition of a single leading underscore and a double leading underscore respectively.

Example -

In below example, the attribute _nonmangled_attribute is marked as nonmangled by convention, but can still be accessed from outside the class.

The attribute __mangled_attribute is private and its name is "mangled" to _MyClass__mangled_attribute, so it can't be accessed directly from outside the class, but you can access it by calling _MyClass__mangled_attribute

class MyClass:
    def __init__(self):
        self._nonmangled_attribute = "I am a nonmangled attribute"
        self.__mangled_attribute = "I am a mangled attribute"

my_object = MyClass()

print(my_object._nonmangled_attribute) # Output: I am a nonmangled attribute
print(my_object.__mangled_attribute) # Throws an AttributeError
print(my_object._MyClass__mangled_attribute) # Output: I am a mangled attribute

Protected Access Modifier

In Python, the convention for indicating that a member is protected is to prefix its name with a single underscore (_). For example, if a class has a method called _my_method, this indicates that the method should only be accessed by the class itself and its subclasses.

An important point to note is that the single underscore is just a naming convention, and does not provide any protection or restrict access to the member. The syntax we follow to make any variable protected is to write variable name followed by a single underscore (_) ie. _varName.

class Student:
    def __init__(self):
        self._name = "Ram"

    def _funName(self):      # protected method
        return "I am Ram"

class Subject(Student):       #inherited class
    pass

obj = Student()
obj1 = Subject()

# calling by object of Student class
print(obj._name)
print(obj._funName())
# calling by object of Subject class
print(obj1._name)
print(obj1._funName())

Resources Used

You can watch the video of Day#62 by clicking on the below link ๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡

Conclusion

Thanks, guys for going through this blog post. On day 62, I learned about public, private and protected access modifiers in Python. I also learned that in Python there is nothing called an access modifier but this is just a convention of protecting the variables and methods from accessing publicly.

Thank you if you read this post and have found this post useful. I hope you have joined me and are enjoying my magical journey of Python coding. This is it for Day #62

See you in the next one.....


About Me

Hey Guys, I am Chintan Jain from CodeWithJain. I am a trader and content creator. I am also passionate about tech and hence wanted to explore the field of tech. I always wanted to learn to code so I watched many tutorials but procrastinated practicing coding. To get into the habit of coding consistently I am starting to BLOG with HASHNODE on daily basis.

I will document my coding journey from scratch and share my daily learnings in a blog post on HASHNODE. I hope you all will enjoy my content and my coding journey.

So what are you waiting for, smash the FOLLOW and LIKE buttons and follow along my coding journey, a step to create more beautiful digital products and empower people.


ย