AccessLevel ClassVariables
AccessLevel ClassVariables
def getId(self):
return self.employeeId;
e1 = Employee(1)
print(e1.getId())
print("Before setting the Salary:",dir(e1))
e1.salary = 20000
print("\n\nAfter setting the Salary:",dir(e1))
print(e1.salary)
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']
def getId(self):
return self.employeeId;
def getName(self):
return self.name;
e1 = Employee(1,"Ravi",40000)
e1.salary=50000
print(e1.salary)
50000
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/AccessLevelControl.ipynb?download=false 1/7
9/14/23, 3:21 PM AccessLevelControl
def getId(self):
return self.__empId
def getName(self):
return self.name
def __privateHelperFunction(self):
print("In Private Function")
def test(self):
e1 = Employee(1,"Ravi")
print(e1.name)
e1.test()
Ravi
The public method trying to Call Private Function
In Private Function
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)
In [12]: e1.__privateHelperFunction()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Input In [12], in <cell line: 1>()
----> 1 e1.__privateHelperFunction()
localhost:8888/nbconvert/html/pythonlab/lab2/AccessLevelControl.ipynb?download=false 2/7
9/14/23, 3:21 PM AccessLevelControl
In [14]: e1._Employee__privateHelperFunction()
In Private Function
In [15]: print(e1._Employee__empId)
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)
self.teamsize=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")
e1.test()
print("\n\nProtected variable access:",e1._name)
print("\n\nProtected method access:")
e1._protectedHelperFunction()
localhost:8888/nbconvert/html/pythonlab/lab2/AccessLevelControl.ipynb?download=false 3/7
9/14/23, 3:21 PM AccessLevelControl
In [5]: m1 = Manager(2,"Raju",5)
m1.acessProtectedBaseclass()
print("The Dir:\n\n",dir(e1))
In [6]: m1.acessPrivateBaseclassMembers()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Input In [6], in <cell line: 1>()
----> 1 m1.acessPrivateBaseclassMembers()
In [7]: m1 = Manager(1,"Raj",5)
print("\nPublic Member Access:",m1.teamsize);
print("\nProtected Member Access:",m1._name)
print("\nPrivate Member Access:",m1.__employeeId)
In [27]: m1 = Manager(2,"Raju",5)
print("The Dir of subclass:\n\n",dir(m1))
localhost:8888/nbconvert/html/pythonlab/lab2/AccessLevelControl.ipynb?download=false 4/7
9/14/23, 3:21 PM AccessLevelControl
In [8]: print(m1._Employee__employeeId)
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.
def getId(self):
return self.stId;
def getName(self):
return self.name;
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))
class Person:
totalObjects=0 # class member
localhost:8888/nbconvert/html/pythonlab/lab2/AccessLevelControl.ipynb?download=false 5/7
9/14/23, 3:21 PM AccessLevelControl
def __init__(self,name):
self.name = name
@classmethod
def incrementcount(cls):
cls.totalObjects = cls.totalObjects + 1
print("Total objects incremented by one: ",cls.totalObjects)
p1=Person("Ravi")
p2=Person("Kalyan")
print(Person.totalObjects)
Person.incrementcount()
p1.incrementcount()
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/AccessLevelControl.ipynb?download=false 6/7
9/14/23, 3:21 PM AccessLevelControl
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):
Person.totalObjects=Person.totalObjects+1
self.name = name
@staticmethod
def greet():
print("Hello!")
@staticmethod
def major(age):
return age > 18
p1=Person("Ravi")
p2=Person("Kalyan")
p1.greet()
Person.greet()
b1 = Person.major(21)
print(b1)
Hello!
Hello!
True
In [ ]:
localhost:8888/nbconvert/html/pythonlab/lab2/AccessLevelControl.ipynb?download=false 7/7