{"id":968,"date":"2023-01-19T17:11:00","date_gmt":"2023-01-19T11:41:00","guid":{"rendered":"https:\/\/geekpython.in\/?p=968"},"modified":"2023-08-15T14:30:40","modified_gmt":"2023-08-15T09:00:40","slug":"access-modifiers-in-python","status":"publish","type":"post","link":"https:\/\/geekpython.in\/access-modifiers-in-python","title":{"rendered":"Public, Private And Protected Access Modifiers In Python"},"content":{"rendered":"\n<p>Python is an object-oriented programming (OOPs) language in which Classes are integral. Classes are so powerful in object-oriented programming that we can perform high-level tasks like inheritance, abstraction, encapsulation, and polymorphism.<\/p>\n\n\n\n<p>In short, Python classes provide a way to organize code, encapsulate data and behavior, create reusable templates for objects, and implement inheritance. Classes offer a powerful way to organize and manage complex code, promote reusability and make the code easier to read and understand.<\/p>\n\n\n\n<p>We can control the access of the variables and methods inside the Python classes. Access modifiers are used to control access to the variables and methods.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"heading-access-modifiers\"><a href=\"https:\/\/geekpython.in\/access-modifiers-in-python#heading-access-modifiers\"><\/a>Access modifiers<\/h1>\n\n\n\n<p>Access modifiers play an important role in securing the data from unauthorized access and preventing any data exploitation.<\/p>\n\n\n\n<p>Using the underscore (<code>_<\/code>), we can control access to the data inside the Python classes. Python Class has three types of access modifiers:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Public Access Modifier<\/strong><\/li>\n\n\n\n<li><strong>Private Access Modifier<\/strong><\/li>\n\n\n\n<li><strong>Protected Access Modifier<\/strong><\/li>\n<\/ul>\n\n\n\n<p>Let&#8217;s understand those above-mentioned access modifiers one by one.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"heading-public-access-modifier\"><a href=\"https:\/\/geekpython.in\/access-modifiers-in-python#heading-public-access-modifier\"><\/a>Public Access Modifier<\/h1>\n\n\n\n<p>The name &#8220;<strong>Public<\/strong>&#8221; says all about this access modifier the variables and methods declared inside the specific Python class can be accessed by that class and any Python class outside that specific class.<\/p>\n\n\n\n<p>Public methods are accessible outside the class and with the help of objects the public methods can be invoked inside the class.<\/p>\n\n\n\n<p>All the variables and methods in a Python class are&nbsp;<strong>public<\/strong>&nbsp;by default and just like mentioned above can be accessed from outside the class environment. Here&#8217;s an example that will help us understand better.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">class Hero:\n    def __init__(self, real_name, reel_name, hero_name):\n        self.real_name = real_name\n        self.reel_name = reel_name\n        self.hero_name = hero_name\n\nhero = Hero(\"RDJ\", \"Tony Stark\", \"Iron Man\")\n\nprint(\"Real name: \", hero.real_name)\nprint(\"Reel name: \", hero.reel_name)\nprint(\"Hero name: \", hero.hero_name)<\/pre><\/div>\n\n\n\n<p>In the above code, we defined a Python class named&nbsp;<code>Hero<\/code>&nbsp;in which we created a constructor that accepts three arguments named&nbsp;<code>real_name<\/code>,&nbsp;<code>reel_name<\/code>, and&nbsp;<code>hero_name<\/code>.<\/p>\n\n\n\n<p>Then we created a variable called&nbsp;<code>hero<\/code>&nbsp;outside the class and instantiated the class&nbsp;<code>Hero<\/code>&nbsp;with corresponding arguments and then printed the values.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Real name:  RDJ\nReel name:  Tony Stark\nHero name:  Iron Man<\/pre><\/div>\n\n\n\n<p>Here,&nbsp;<code>real_name<\/code>,&nbsp;<code>reel_name<\/code>&nbsp;and&nbsp;<code>hero_name<\/code>&nbsp;are public data members and can be used anywhere in the program. We can also create a public member function inside the class and access it. The following example will show how to do it.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">class Hero:\n    def __init__(self, real_name, reel_name, hero_name):\n        self.real_name = real_name\n        self.reel_name = reel_name\n        self.hero_name = hero_name\n\n    def display_name(self):\n        print(\"Real name :\", self.real_name)\n        print(\"Reel name :\", self.reel_name)\n\nhero = Hero(\"Chris Evans\", \"Steve Rogers\", \"Captain America\")\nhero.display_name()\nprint(\"Hero name: \", hero.hero_name)<\/pre><\/div>\n\n\n\n<p>In the above code,&nbsp;<code>display_name<\/code>&nbsp;is a public member function and we accessed it outside the class. The code will run without any errors.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Real name : Chris Evans\nReel name : Steve Rogers\nHero name:  Captain America<\/pre><\/div>\n\n\n\n<p>We can use these variables in other functions also and the following code shows how to do it.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">def access_public_data():\n    x = Hero(\"Andrew Garfield\", \"Peter Parker\", \"Spider-man\")\n    print(\"Real name: \", x.real_name)\n    print(\"Reel name: \", x.reel_name)\n    print(\"Hero name: \", x.hero_name)\n\naccess_public_data()<\/pre><\/div>\n\n\n\n<p>We created a function called&nbsp;<code>access_public_data<\/code>&nbsp;and instantiated the class&nbsp;<code>Hero<\/code>&nbsp;which we made earlier and passed the required arguments and called that function. Since the variables inside the&nbsp;<code>Hero<\/code>&nbsp;class are public, the code will run without any error.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Real name:  Andrew Garfield\nReel name:  Peter Parker\nHero name:  Spider-man<\/pre><\/div>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"heading-protected-access-modifier\"><a href=\"https:\/\/geekpython.in\/access-modifiers-in-python#heading-protected-access-modifier\"><\/a>Protected Access Modifier<\/h1>\n\n\n\n<p>Protected variables and methods are accessible within the specific class environment and can also be accessed by the sub-classes. We can also say that it allows the resources of the parent class to be inherited by the child class.<\/p>\n\n\n\n<p>Any variables or methods prefixed with a&nbsp;<strong>single underscore<\/strong>&nbsp;(<code>_<\/code>) in a class are&nbsp;<strong>protected<\/strong>&nbsp;and can be accessed within the specific class environment. The protected variables\/methods can be accessed inside the sub-classes of the parent class.<\/p>\n\n\n\n<p>Here is a code to make protected variables\/methods inside the Python class.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">class Anime:\n    _rating = \"Best\"\n    def __init__(self, anime, release_year):\n        self._anime = anime\n        self._release_year = release_year\n\n    def _show(self):\n        print(\"Release:\", self._release_year)\n\nobj = Anime(\"Naruto\", 2002)\nprint(\"Anime:\", obj._anime)\nobj._show()<\/pre><\/div>\n\n\n\n<p>In the above code,&nbsp;<code>_anime<\/code>&nbsp;and&nbsp;<code>_release_year<\/code>&nbsp;which are protected instance variables inside the class&nbsp;<code>Anime<\/code>&nbsp;as well as it has a protected function called&nbsp;<code>_show<\/code>.<\/p>\n\n\n\n<p>In the next block of code, we instantiated the class&nbsp;<code>Anime<\/code>&nbsp;and passed the required arguments and stored them inside the object named&nbsp;<code>obj<\/code>&nbsp;then displayed the result by calling the&nbsp;<strong>protected<\/strong>&nbsp;function and variable.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Anime: Naruto\nRelease: 2002<\/pre><\/div>\n\n\n\n<p>We can also access these protected instance variables and protected functions inside the derived class.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \"># Derived class\nclass Other_Anime(Anime):\n    def __init__(self, anime, year):\n        Anime.__init__(self, anime, year)\n\n    def show_anime(self):\n        print(\"Anime:\", self._anime)\n        self._show()\n\nx = Other_Anime(\"Demon Slayer\", 2019)\nx.show_anime()<\/pre><\/div>\n\n\n\n<p>In the above code, the class&nbsp;<code>Other_Anime<\/code>&nbsp;is created which inherits the class&nbsp;<code>Anime<\/code>&nbsp;and we defined the public function named&nbsp;<code>show_anime<\/code>&nbsp;that accesses the&nbsp;<strong>protected<\/strong>&nbsp;variables of the class&nbsp;<code>Anime<\/code>.<\/p>\n\n\n\n<p>We called the&nbsp;<strong>public<\/strong>&nbsp;function to display the result from the protected variables.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Anime: Demon Slayer\nRelease: 2019<\/pre><\/div>\n\n\n\n<p>You might be thinking that&nbsp;<strong>protected variables<\/strong>&nbsp;of the class&nbsp;<code>Anime<\/code>&nbsp;were also accessible outside the class environment. The protected variables and functions can be accessed by the derived classes and any other classes but it is the sole responsibility of the good programmer not to use the&nbsp;<strong>protected data members<\/strong>&nbsp;outside the specific class environment.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"heading-private-access-modifier\"><a href=\"https:\/\/geekpython.in\/access-modifiers-in-python#heading-private-access-modifier\"><\/a>Private Access Modifier<\/h1>\n\n\n\n<p>As we can tell by seeing its name the &#8220;<strong>Private<\/strong>&#8221; access modifier restricts the variables and methods declared inside the specific class to that class environment.<\/p>\n\n\n\n<p>Simply put, the variables and methods declared inside a class can be accessed inside that class environment and not outside that class. Python doesn&#8217;t have any mechanism restricting access to the variables or methods.<\/p>\n\n\n\n<p>But there is a way by which we can impose restrictions to access the variables and methods in Python. Python suggests using a&nbsp;<strong>double underscore<\/strong>&nbsp;to imitate the behavior of the private access modifier.<\/p>\n\n\n\n<p>Variables and methods prefixed with a&nbsp;<strong>double underscore<\/strong>&nbsp;(<code>__<\/code>) make them private and cannot be accessed outside the specific class. Let&#8217;s understand it with an example.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">class Superhero:\n    __hero = \"Iron Man\"\n\n    def __init__(self, name):\n        self.__name = name\n\nobj = Superhero(\"Shaktiman\")\nprint(obj.__name)<\/pre><\/div>\n\n\n\n<p>In the above code, the class&nbsp;<code>Superhero<\/code>&nbsp;is created and we created the private variable named&nbsp;<code>__hero<\/code>&nbsp;and a private instance variable named&nbsp;<code>__name<\/code>. Then we instantiated the class and passed the required arguments and tried to access the&nbsp;<strong>private data<\/strong>.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Traceback (most recent call last):\n  ...\n    print(obj.__name)\nAttributeError: 'Superhero' object has no attribute '__name'<\/pre><\/div>\n\n\n\n<p>We got the&nbsp;<strong>AttributeError<\/strong>&nbsp;saying that the class&nbsp;<code>Superhero<\/code>&nbsp;has no attribute called&nbsp;<code>__name<\/code>&nbsp;and it happened because the private data in a class cannot be accessed outside the class. But we can access the private variables and methods inside the class.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">class Superhero:\n    def __init__(self, name):\n        self.__name = name\n\n    def displayname(self):\n        print(\"Hero:\", self.__name)\n\nobj = Superhero(\"Shaktiman\")\nobj.displayname()<\/pre><\/div>\n\n\n\n<p>In the above code, we created a public function called&nbsp;<code>displayname<\/code>&nbsp;that accesses the private variable&nbsp;<code>__name<\/code>&nbsp;inside the class and we tried to print the output.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Hero: Shaktiman<\/pre><\/div>\n\n\n\n<p>The code ran without any error and we got the output that we expected.<\/p>\n\n\n\n<p>Python prevents private data from accessing outside the class so it does&nbsp;<strong>name mangling<\/strong>&nbsp;which means that it changes the process of accessing private data.<\/p>\n\n\n\n<p>We can&nbsp;<strong>access the private data<\/strong>&nbsp;from the class and the following example will show you how to do it.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">class Superhero:\n    __hero = \"Iron Man\"\n\n    def __init__(self, name):\n        self.__name = name\n\nobj = Superhero(\"Shaktiman\")\nprint(obj._Superhero__name)\nprint(obj._Superhero__hero)<\/pre><\/div>\n\n\n\n<p>We tried the&nbsp;<strong>name-mangling<\/strong>&nbsp;process that helps us access the variables outside the class. We added the&nbsp;<code>_Superhero<\/code>&nbsp;which is the name of our base class and then added the private variable to the class object&nbsp;<code>obj<\/code>.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Shaktiman\nIron Man<\/pre><\/div>\n\n\n\n<p>We successfully accessed the&nbsp;<code>__name<\/code>&nbsp;and&nbsp;<code>__hero<\/code>&nbsp;variables outside the class.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"heading-conclusion\"><a href=\"https:\/\/geekpython.in\/access-modifiers-in-python#heading-conclusion\"><\/a>Conclusion<\/h1>\n\n\n\n<p>Python uses a specific naming convention to make any variables\/methods protected and private inside the class and all the variables and methods defined inside the Python class are public by default.<\/p>\n\n\n\n<p>Public data attributes are accessible by any class and function, protected data attributes should only be accessed inside the class environment and can also be accessed inside the sub-classes and private data attributes are only accessible inside the class.<\/p>\n\n\n\n<p>We have learned about the public, protected, and private access modifiers that are used to impose restrictions on accessing the variables and methods of the Python class.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\ud83c\udfc6<strong>Other articles you might like if you liked this article<\/strong><\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/f-string-in-python\" rel=\"noreferrer noopener\">A modern way to perform string interpolation using f-string in Python<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/integrate-postgresql-database-in-python\" rel=\"noreferrer noopener\">Integrate the PostgreSQL database with Python<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/using-transfer-learning-for-deep-learning-model\" rel=\"noreferrer noopener\">Build a custom deep-learning model using the transfer learning technique<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/different-ways-to-reverse-a-python-list\" rel=\"noreferrer noopener\">8 different ways by which you can reverse a Python list<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/one-liners-in-python\" rel=\"noreferrer noopener\">Powerful one-liners in Python to enhance your code<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/multiple-inputs-in-python\" rel=\"noreferrer noopener\">Take multiple inputs from the user in a single line in Python<\/a>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><strong>That&#8217;s all for now<\/strong><\/p>\n\n\n\n<p><strong>Keep Coding\u270c\u270c<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python is an object-oriented programming (OOPs) language in which Classes are integral. Classes are so powerful in object-oriented programming that we can perform high-level tasks like inheritance, abstraction, encapsulation, and polymorphism. In short, Python classes provide a way to organize code, encapsulate data and behavior, create reusable templates for objects, and implement inheritance. Classes offer [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":971,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ocean_post_layout":"","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"0","ocean_second_sidebar":"0","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"0","ocean_custom_header_template":"0","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"0","ocean_menu_typo_font_family":"0","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"0","ocean_post_oembed":"","ocean_post_self_hosted_media":"","ocean_post_video_embed":"","ocean_link_format":"","ocean_link_format_target":"self","ocean_quote_format":"","ocean_quote_format_link":"post","ocean_gallery_link_images":"off","ocean_gallery_id":[],"footnotes":""},"categories":[2],"tags":[12,31],"class_list":["post-968","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-python","tag-python3","entry","has-media"],"_links":{"self":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/968","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/comments?post=968"}],"version-history":[{"count":3,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/968\/revisions"}],"predecessor-version":[{"id":1317,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/968\/revisions\/1317"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media\/971"}],"wp:attachment":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media?parent=968"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/categories?post=968"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/tags?post=968"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}