Python 3

home

Introduction to Python

davidbpython.com




'setter' and 'getter' Methods and Encapsulation


setter and getter methods

These methods are used to control the reading and writing of instance attributes.


class Counter:

    # a 'setter' method
    def __init__(self, val):
        if not isinstance(val, int):
            raise TypeError('arg must be an int')

        self.value = val       # set the value in the instance's attribute

    # a 'getter' method
    def getval(self):
        return self.value

    def increment(self):
        self.value = self.value + 1


a = Counter(10)

b = Counter('hello')    # TypeError:  arg must be an int


Ex. 13.10






breaking encapsulation

Encapsulation means that data integrity is maintained.


class Counter:

    def __init__(self, val):
        if not isinstance(val, int):
            raise TypeError('arg must be an int')

        self.value = val       # set the value in the instance's attribute

    def getval(self):
        return self.value

    def increment(self):
        self.value = self.value + 1


a = Counter(10)

a.value = 'hello'      # <-- here we are breaking encapsulation

a.increment()          # (unexpected TypeError)






data object example

Objects are often used to represent a 'record' of data.


file records.csv

Janice,Korz,31
Adam,Elbert,29
Jake,Broom,30
Alice,Kim,41
Amber,Post,50
Eun-Kyung,Choi,33

class Student:
    def __init__(self, fname, lname, age):
        self.first = fname
        self.last = lname
        self.age = age


students = []                     # list to hold Student objects
for line in open('records.csv'):
    fn, ln, ag = line.split(',')
    stu = Student(fn, ln, ag)     # construct a new Student
    students.append(stu)          # add to the student list

for stu in students:              # loop through the list of Student objects
    print(stu.fname)              # print each student's name

Adam
Jake
Alice
Amber
Eun-Kyung






Study Glossary for OOP, Part I

These are OOP terms we introduced in this session.


class A statement that defines a new type, and the attributes and methods that define the object's data and behavior.
instance An object of the type defined in the class. Calling the class produces a new instance. The instance will have access to the methods defined in the class, but hold its own data values ("state") in its attributes.
object See "instance".
method A function defined in and as part of a class.
attribute A value associated with an object. An "instance attribute" represents data stored in an instance. A "class attribute" represents data defined in a class, also known as a class variable.
constructor The __init__ method, which defines the attributes in a new instance that is being created.
initialize Define first values for any object. __init__ is so called because it sets attribute values in a new instance.
state Refers to the values stored in the instance. An instance's state is most often changed by the __init__ constructor and "setter" methods, but may be changed at any point.
setter and getter methods Methods that are designed to either write to or read from an instance.
encapsulation The technique of controlling instance state (i.e., the values of its attributes) through methods designed for this purpose.





[pr]