Public, Private, And Protected Access Specifiers
# no underscore(_) means it is public - anyone can access it
#
# with one underscore(_) means it is protected - only the one in the class and the ones who are accessing
# the class can access it
#
# with 2 underscore(_) means it is private - means can be used only by the class using a special code
# if we try to access it without that code python will error as no attribute found and the code is in the code.
# code to access private variable :
# print(emp._Employee__pr)
# Code for public is
class employee:
def __init__(self, name, age):
self.name = name
self.age = age
#
# Code for protected is
class employee:
def __init__(self, name, age):
self._name = name # protected attribute
self._age = age # protected attribute
#Code For private is
class employee:
def __init__(self, name, age):
self.__name = name # private attribute
self.__age = age # private attribute
# Name mangling in Python:
# Python does not have any strict rules when it comes to public, protected or private, like java.
# So, to protect us from using the private attribute in any other class,
# Python does name mangling, which means that every member with
# a double underscore will be changed to _object._class__variable when trying to call using an object.
# The purpose of this is to warn a user, so he does not use any private class variable
# or function by mistake without realizing it's states.
# Code :
# Public -
# Protected -
# Private -
class Employee:
no_of_leaves = 8
var = 8
_protec = 9
__pr = 98
def __init__(self, aname, asalary, arole):
self.name = aname
self.salary = asalary
self.role = arole
def printdetails(self):
return f"The Name is {self.name}. Salary is {self.salary} and role is {self.role}"
@classmethod
def change_leaves(cls, newleaves):
cls.no_of_leaves = newleaves
@classmethod
def from_dash(cls, string):
return cls(*string.split("-"))
@staticmethod
def printgood(string):
print("This is good " + string)
emp = Employee("harry", 343, "Programmer")
print(emp._Employee__pr)
Comments
Post a Comment