Wednesday, May 10, 2023

What is double and single underscore meaning in Python

 While none of this is strictly enforced by python, the naming convention of a double underscore means "private", while a single underscore means "protected".


A double underscore is meant to protect subclasses from causing errors by using the same name. By namespacing them by class name, the defining class can be sure its variables will remain valid.


A single underscore means that subclasses are free to access and modify those same attributes, being shared with the super class.


Both forms suggest that any outside class should not be accessing these.


class A(object):


    __private = 'private'

    _protected = 'protected'


    def show(self):

        print self.__private 

        print self._protected


class B(A):

    __private = 'private 2'

    _protected = 'protected 2'


a = A()

a.show()

#private

#protected


b = B()

b.show()

#private

#protected 2

This example shows that even though class B defined a new __private, it does not affect the inherited show method, which still accesses the original superclass attribute. _protected is however modified and the superclass show method reflects this, because they are the same attribute.


references:

https://stackoverflow.com/questions/12117087/python-hide-methods-with

No comments:

Post a Comment