0% found this document useful (0 votes)
15 views33 pages

Lesson 03 - Accessors & Mutators

Uploaded by

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

Lesson 03 - Accessors & Mutators

Uploaded by

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

Accessors & Mutators

Why use classes at all?

• Classes and objects are more like the real world. They
minimize the semantic gap by modeling the real world
more closely

• The semantic gap is the difference between the real world


and the representation in a computer

• Do you care how your TV works?


– No… you are a user of the TV, the TV has operations and
they work. You don’t care how internal circuits are working.
Why use classes at all?
• Classes and objects allow you to define
an interface to some object (it’s
operations) and then use them without
know the internals

• Defining classes helps modularize your


program into multiple objects that work
together, that each have a defined
purpose
Encapsulation

• Attributes and behaviors are enclosed (encapsulated)


within the logical boundary of the object entity

– In structured or procedural systems, data and code are


typically maintained as separate entities (e.g., modules
and data files)

– In Object Technology systems, each object contains the


data (attributes) and the code (behaviors) that operates
upon those attributes
Abstraction

• Encapsulation implements the concept of


abstraction:
– details associated with object sub-
components are enclosed within the
logical boundary of the object
– user of object only “sees” the public
interface of the object, all the internal
details are hidden example print(),
input(),len()etc
Abstraction

• Encapsulation makes abstraction possible


Abstraction in your life
Abstraction in your life

• You know the public interface. Do you


know implementation details? Do you
care?

• As long as the public interface stays the


same, you don’t care about
implementation changes e.g print()
Think?
• Should class attributes be accessed in
driver program and can be set?
like
ali=Person(“ali”)
ali.age=27
Think it of like a personal diary. Should the
content(attribute) be accessed and modified
by someone else?
Think?
• Sometimes NO for critical applications like
bank_balance attribute in a banking class must
not be accessed and modified outside the
class.
• OOP languages like C++/ Java implement
attributes as private---Opaque Capsule
• OOP in python implement attributes as public
like transparent capsule
Implementing Public/Private Interfaces

• In Java/ c++ you will be able to enforce


access restrictions on your instance
variables… you can (and should) make
them private so Java itself enforces data
encapsulation.

• So… does Python support “private”


instance variables? Yes (and no)
Implementing Public/Private Interfaces

• Private attributes / functions cannot be


accessed outside the class
• Can we ENFORCE use of getters and
setters?
• If I design a class I would like to make
sure no one can access my class
attributes directly, they MUST use my
getters and setters.
Implementing Public/Private Interfaces

• Python attributes and methods are


public by default.
– public attributes: any other class or
function can see and change the attribute
myCircle.radius = 20
– public method: any other class or
function can call the method
myCircle.method1()
Implementing Public/Private Interfaces

• Private attributes can (almost) only be


accessed by methods defined in the class
• Private methods can (almost) only be
called by other methods defined in the
class
• Idea: Everything defined in the class has
access to private parts.
Hiding your private parts (in Python)

• You can create somewhat private parts in


Python. Naming an instance variable with an
__ (two underscores) makes it private
Hiding your private parts (in Python)

Gives Error
Hiding your private parts (in Python)
• Be a little sneakier then.. use __name:
Hiding your private parts (in Python)
• Be super sneaky then.. use _Student__name:
Hiding your private parts (in Python)
• So, it is possible to interact with private data in
Python, but it is difficult to hide them
completely and good programers know not to
do it.
• Using the defined interface methods (getters
and setters) will make code more
maintainable and safer to use. Setters and
getters provide abstraction.
Getters & Setters (or)
Accessors & Mutators
• These methods are a coding convention
• Getters/Accessors are methods that return an
attribute
def get_name(self):
• Setters/Mutators are methods that set an
attribute
def set_name(self,newName):
Why use getters?

• Definition of my getter:
def getName(self):
return self.name
• What if I want to store the name instead as first
and last name in the class? Well, with the getter
I only have to do this:
def getName(self):
return self.firstname + self.lastname
Why use getters?
• If I had used dot notation outside the class,
then all the code OUTSIDE the class would
need to be changed because the internal
structure INSIDE the class changed.

• Getters help you hide the internal structure of


your class!
Why use getters?
• Think about libraries of code… If the Python-authors
change how the Button class works, do you want to
have to change YOUR code? No! Encapsulation helps
make that happen. They can change anything inside
they want, and as long as they don’t change the
method signatures(function headers), your code will
work fine. E.g print() func functionality can be modified
at back end by python developers but you don’t have to
change your own code wherever you have used print()
command because function header is not changed
Setters

• Anoter common method type are “setters”


def setAge(self, age):
self.age = age
• Why? Same reason + one more. I want to hide the internal
structure of my Class, so I want people to go through my
methods to get and set instance variables. What if I wanted
to start storing people’s ages in dog-years? Easy with setters:
def setAge(self, age):
self.age = age / 7
Setters
• More commonly, what if I want to add validation…
for example, no age can be over 200 or below 0? If
people use dot notation, I cannot do it. With setters:

def setAge(self, age):


if age > 200 or age < 0:
# show error
else:
self.age = age / 7
Getters and Setters

• Getters and setters are useful to provide


data encapsulation and abstraction. They
hide the internal structure of your class
and they should be used!
Example
Example
Example
class Student:
def __init__(self,n,a):
#self.__name=n
#self.__age=a
#use of setters in constructors
self.setName(n)
self.setAge(a)
def setName(self,n):
self.__name=n
def setAge(self,a):
if a<100 and a>0
self.__age=a
else:
raise ValueError(“Age is not proper!”)
def getName(self):
return self.__name
def getAge(self):
return self.__age
def display(self):
print("Name: ", self.__name, "Age: ", self.__age)
Example
s1=Student("Ali",22)
s2=Student("Ahmad",23)
a=s1.__age #gives error--use getter
s1.__age=34 #cannot set this way-use setters
s1.display()# age for s1 is not modified, it is still 22
s1.setAge(34)
s1.display()
s2.display()
Private Methods
• Private methods in Python are denoted by a
double underscore prefix before the method
name (e.g. __private_method).
• Private methods are meant to be used only
within the class and should not be accessed
from outside the class
Example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def __private_method(self):
print('This is a private method.')

person = Person('John Doe', 30)


person.__private_method() # AttributeError:
Task
• Modify the Room class with private attributes,
proper accessors & mutators. Also, update the
class constructor as well. Make some private
functions also.

You might also like