0% found this document useful (0 votes)
6 views7 pages

AccessLevel ClassVariables

Uploaded by

pardhapradeep824
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views7 pages

AccessLevel ClassVariables

Uploaded by

pardhapradeep824
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

9/14/23, 3:21 PM AccessLevelControl

Access Levels and class variables


In [2]: class Employee():
def __init__(self, employeeId):
self.employeeId=employeeId

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']

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):
self.employeeId=employeeId
self.name=name
self.salary=sal

def getId(self):
return self.employeeId;

def getName(self):
return self.name;

e1 = Employee(1,"Ravi",40000)
e1.salary=50000
print(e1.salary)

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/AccessLevelControl.ipynb?download=false 1/7
9/14/23, 3:21 PM AccessLevelControl

In [1]: class Employee:


def __init__(self, employeeId, name):
self.__empId=employeeId # private
self.name=name # public

def getId(self):
return self.__empId

def getName(self):
return self.name

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(e1.name)
e1.test()

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/AccessLevelControl.ipynb?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)
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

Calling Protected Function


In Protected Function

Protected variable access: Ravi

Protected method access:


In Protected Function

In [5]: m1 = Manager(2,"Raju",5)

m1.acessProtectedBaseclass()

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]: m1.acessPrivateBaseclassMembers()

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Input In [6], in <cell line: 1>()
----> 1 m1.acessPrivateBaseclassMembers()

Input In [4], in Manager.acessPrivateBaseclassMembers(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:",m1.teamsize);
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:",m1.teamsize);
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/AccessLevelControl.ipynb?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):
self.stId=id
self.name=name
self.avg = avg

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))

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/AccessLevelControl.ipynb?download=false 5/7
9/14/23, 3:21 PM AccessLevelControl

def __init__(self,name):

# different ways to access class member.


Person.totalObjects=Person.totalObjects+1 # Option 1
#self.__class__.totalObjects= self.__class__.totalObjects+1 # Option 2
#type(self).totalObjects= type(self).totalObjects+1 # Option 3

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

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):
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

You might also like