9/14/23, 3:21 PM AccessLevelControl
Access Levels and class variables
In [2]: class Employee():
def __init__(self, employeeId):
[Link]=employeeId
def getId(self):
return [Link];
e1 = Employee(1)
print([Link]())
print("Before setting the Salary:",dir(e1))
[Link] = 20000
print("\n\nAfter setting the Salary:",dir(e1))
print([Link])
1
Before setting the Salary: ['__class__', '__delattr__', '__dict__', '__dir__', '__
doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash_
_', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', '__weakref__', 'employeeId', 'getId']
After setting the Salary: ['__class__', '__delattr__', '__dict__', '__dir__', '__d
oc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__',
'__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__ne
w__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__s
tr__', '__subclasshook__', '__weakref__', 'employeeId', 'getId', 'salary']
20000
By default everything is public.
In [13]: class Employee:
def __init__(self, employeeId, name, sal):
[Link]=employeeId
[Link]=name
[Link]=sal
def getId(self):
return [Link];
def getName(self):
return [Link];
e1 = Employee(1,"Ravi",40000)
[Link]=50000
print([Link])
50000
Access levels: public, protected, private
Private: prefix by two underscores. Can be for variables and also for methods. Python
performs name mangling of private variables. Every member with double underscore will be
changed to: _classname__variable.
localhost:8888/nbconvert/html/pythonlab/lab2/[Link]?download=false 1/7
9/14/23, 3:21 PM AccessLevelControl
In [1]: class Employee:
def __init__(self, employeeId, name):
self.__empId=employeeId # private
[Link]=name # public
def getId(self):
return self.__empId
def getName(self):
return [Link]
def __privateHelperFunction(self):
print("In Private Function")
def test(self):
print("The public method trying to Call Private Function")
self.__privateHelperFunction()
e1 = Employee(1,"Ravi")
print([Link])
[Link]()
Ravi
The public method trying to Call Private Function
In Private Function
Attempting to call private members using object reference.
In [11]: #Following line gives an error when attempting to accessing private members
print(e1.__employeeId) # error
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Input In [11], in <cell line: 2>()
1 #Following line gives an error when attempting to accessing private member
s
----> 2 print(e1.__employeeId)
AttributeError: 'Employee' object has no attribute '__employeeId'
In [12]: e1.__privateHelperFunction()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Input In [12], in <cell line: 1>()
----> 1 e1.__privateHelperFunction()
AttributeError: 'Employee' object has no attribute '__privateHelperFunction'
In [13]: print("\n\nThe directory :",dir(e1))
The directory : ['_Employee__empId', '_Employee__privateHelperFunction', '__class_
_', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge
__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '_
_le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex_
_', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__wea
kref__', 'getId', 'getName', 'name', 'test']
localhost:8888/nbconvert/html/pythonlab/lab2/[Link]?download=false 2/7
9/14/23, 3:21 PM AccessLevelControl
Workaround to call the private methods.
In [14]: e1._Employee__privateHelperFunction()
In Private Function
Backdoor to access: private attribute changes to: object._class__variable.
In [15]: print(e1._Employee__empId)
Protected(prefix by one under score). Accessible from subclasses.
In [4]: class Employee:
def __init__(self, employeeId, name):
self.__employeeId=employeeId # private
self._name=name #protected
def getId(self):
return self.__employeeId;
def getName(self):
return self._name;
def _protectedHelperFunction(self):
print("In Protected Function")
def test(self):
print("Calling Protected Function")
self._protectedHelperFunction()
class Manager(Employee):
def __init__(self, employeeId, name,teamsize):
Employee.__init__(self, employeeId, name)
[Link]=teamsize # public
def acessPrivateBaseclassMembers(self):
print("\n\nAccessing Private Baseclass member",self.__employeeId) # Can not
def acessProtectedBaseclass(self):
print("\n\nAccessing Protected Baseclass member",self._name) # Can access p
e1 = Employee(2,"Ravi")
[Link]()
print("\n\nProtected variable access:",e1._name)
print("\n\nProtected method access:")
e1._protectedHelperFunction()
localhost:8888/nbconvert/html/pythonlab/lab2/[Link]?download=false 3/7
9/14/23, 3:21 PM AccessLevelControl
Calling Protected Function
In Protected Function
Protected variable access: Ravi
Protected method access:
In Protected Function
In [5]: m1 = Manager(2,"Raju",5)
[Link]()
print("The Dir:\n\n",dir(e1))
Accessing Protected Baseclass member Raju
The Dir:
['_Employee__employeeId', '__class__', '__delattr__', '__dict__', '__dir__', '__d
oc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__',
'__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__ne
w__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__s
tr__', '__subclasshook__', '__weakref__', '_name', '_protectedHelperFunction', 'ge
tId', 'getName', 'test']
In [6]: [Link]()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Input In [6], in <cell line: 1>()
----> 1 [Link]()
Input In [4], in [Link](self)
29 def acessPrivateBaseclassMembers(self):
---> 30 print("\n\nAccessing Private Baseclass member",self.__employeeId)
AttributeError: 'Manager' object has no attribute '_Manager__employeeId'
In [7]: m1 = Manager(1,"Raj",5)
print("\nPublic Member Access:",[Link]);
print("\nProtected Member Access:",m1._name)
print("\nPrivate Member Access:",m1.__employeeId)
Public Member Access: 5
Protected Member Access: Raj
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Input In [7], in <cell line: 4>()
2 print("\nPublic Member Access:",[Link]);
3 print("\nProtected Member Access:",m1._name)
----> 4 print("\nPrivate Member Access:",m1.__employeeId)
AttributeError: 'Manager' object has no attribute '__employeeId'
In [27]: m1 = Manager(2,"Raju",5)
print("The Dir of subclass:\n\n",dir(m1))
localhost:8888/nbconvert/html/pythonlab/lab2/[Link]?download=false 4/7
9/14/23, 3:21 PM AccessLevelControl
The Dir of subclass:
['_Employee__employeeId', '__class__', '__delattr__', '__dict__', '__dir__', '__d
oc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__',
'__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__ne
w__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__s
tr__', '__subclasshook__', '__weakref__', '_name', '_protectedHelperFunction', 'ac
essPrivateBaseclassMembers', 'acessProtectedBaseclass', 'getId', 'getName', 'teams
ize', 'test']
In [8]: print(m1._Employee__employeeId)
class members, class methods:
A class method is a method which is bound to the class and not the object of the class. They
have the access to the state of the class as it takes a class parameter that points to the class
and not the object instance. It can modify a class state that would apply across all the
instances of the class. For example it can modify a class variable that will be applicable to all
the instances.
In [9]: class Student:
def __init__(self, id, name,avg):
[Link]=id
[Link]=name
[Link] = avg
def getId(self):
return [Link];
def getName(self):
return [Link];
s1 = Student(1,"Ravi",7.5)
s2 = Student(2,"Raj",7.5)
s3 = Student(3,"Kavya",7.5)
In Python every thing is an Object. We can get the class from which the object created by
either class (in herited from base class 'object') or type()
In [10]: x = 5
y = 7.5
print("x class",x.__class__)
print("x class",type(x))
print("y class",y.__class__)
print("y class",type(y))
x class <class 'int'>
x class <class 'int'>
y class <class 'float'>
y class <class 'float'>
In [11]: #%% class members, class methods
# class methods marked with @classmethod and takes 'cls' as first argument
class Person:
totalObjects=0 # class member
localhost:8888/nbconvert/html/pythonlab/lab2/[Link]?download=false 5/7
9/14/23, 3:21 PM AccessLevelControl
def __init__(self,name):
# different ways to access class member.
[Link]=[Link]+1 # Option 1
#self.__class__.totalObjects= self.__class__.totalObjects+1 # Option 2
#type(self).totalObjects= type(self).totalObjects+1 # Option 3
[Link] = name
@classmethod
def incrementcount(cls):
[Link] = [Link] + 1
print("Total objects incremented by one: ",[Link])
p1=Person("Ravi")
p2=Person("Kalyan")
print([Link])
[Link]()
[Link]()
dir(Person)
2
Total objects incremented by one: 3
Total objects incremented by one: 4
['__class__',
Out[11]:
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',
'incrementcount',
'totalObjects']
A static method is also a method which is bound to the class and not the object of the class.
A static method can’t access or modify class state. It is present in a class because it makes
sense for the method to be present in class.
Utility functions that can be computed from all the parameter passed. They do not need any
Object or class state to perform the task.
localhost:8888/nbconvert/html/pythonlab/lab2/[Link]?download=false 6/7
9/14/23, 3:21 PM AccessLevelControl
In [12]: def major(age):
return age > 18
print(major(15))
False
In [29]: # static methods marked with @staticmethod and it neither takes 'self' nor 'cls' as
# static methods can be either called by using an object or a class.
class Person:
totalObjects=0 # class member
def __init__(self,name):
[Link]=[Link]+1
[Link] = name
@staticmethod
def greet():
print("Hello!")
@staticmethod
def major(age):
return age > 18
p1=Person("Ravi")
p2=Person("Kalyan")
[Link]()
[Link]()
b1 = [Link](21)
print(b1)
Hello!
Hello!
True
In [ ]:
localhost:8888/nbconvert/html/pythonlab/lab2/[Link]?download=false 7/7