Introduction to Object Oriented Programming

Overview

What is procedural programming?

Why do we use procedural programming?

Why do we not use procedural programming?

Why do we use OOP?

Object Oriented Programming (OOP)

The 3 aspects of an object



Classes

Class naming conventions



Encapulsation

Encapsulation

Sample

class Person(object): ## class signature
    ## constructor
    def __init__(self, first_name, last_name, age):
        self.first_name = first_name
        self.last_name = last_name
def main():
    person = Person("Leon", "Hunter", 27)

if __name__ == '__main__':
    main()

Instance-Functions (Methods)

Instance-Variables (Fields)



Constructors

Nullary Constructor

Sample

class Person(object): ## class signature

	def __init__(self): ## constructor signature
        print("A person object has been created")
def main():
    person = Person()

if __name__ == '__main__':
    main()
A person object has been created

Default Constructor

Sample

class Person(object): ## class signature
    ## no constructor defined

    def say_hello():
        print("Hello")
def main():
    person = Person()
A person object has been created

Non-nullary Constructor

Sample

class Person(object): ## class signature
    ## constructor
    def __init__(self, first_name, last_name, age):
        self.first_name = first_name
        self.last_name = last_name
def main():
    leon = Person("Leon", "Hunter", 27)


if __name__ == '__main__':
    main()


Setters
(Mutators)

Sample

class Person(object): ## class signature
    ## constructor
    def __init__(self, first_name, last_name, age):
        self.first_name = first_name
        self.last_name = last_name

    def set_first_name(self, new_first_name):
        self.first_name = new_first_name

    def set_last_name(self, new_last_name):
        self.first_name = new_last_name
def main():
    leon = Person("Leon", "Hunter", 27)
    bob_first_name = "Robert"
    leon.set_first_name(bob_first_name)


if __name__ == '__main__':
    main()

Getters
(Accessors)

Sample

class Person(object): ## class signature
    ## constructor
    def __init__(self, first_name, last_name, age):
        self.first_name = first_name
        self.last_name = last_name

    def set_first_name(self, new_first_name):
        self.first_name = new_first_name

    def set_last_name(self, new_last_name):
        self.first_name = new_last_name
def main():
    leon = Person("Leon", "Hunter", 27)
    bob_first_name = "Robert"
    leon.set_first_name(bob_first_name)
    leon_new_first_name = leon.get_first_name()
    print(leon_new_first_name)


if __name__ == '__main__':
    main()
Robert