Search Header Logo
OOP Concepts

OOP Concepts

Assessment

Presentation

Computers, Science

University

Hard

Created by

Vaishnavi Sundararajan

Used 1+ times

FREE Resource

9 Slides • 0 Questions

1

Object-oriented Programming

2

What?

  • Define an abstract “class” with attributes and functions

  • Objects are instances of this class

  • They can “inherit” these attributes and functions

  • But these can be changed as necessary!​

3

Why?

  • Might have multiple different instances (objects) which behave “similarly”

  • Have similar (but not same) attributes and functions

  • Allows us to reuse code without replicating

  • Also reduces points of error! ​

  • ​Taxonomy always helps

4

How?

  • Define a “parent” class, e.g. mammals

  • ​Some common attributes, e,g. title, habitat

  • ​Can define instances, e.g. dog, elephant, blue whale

  • ​Each of these has a title and a habitat

  • The __init__ function for the class specifies how to initialize instances

5

Example

class mammals:

………… title = “”

………… habitat = “”​

………… def __init__(self, title, habitat) :

………………………. self.title = title​

………………………. self.habitat = habitat​

​………… def showatt(self) :

…………………print(self.title, self.habitat, sep=“ lives in ”)

​dog = mammals(“dog”, “kennel”)

ele = mammals(“elephant”, “forest”)

6

Inheritance

  • What if I want to define classes which only share some attributes?

  • Consider a class for people. All people have a name and an age.

  • Now consider a class for UCSC students. Students are people (too?), but they have an ID number, and their GPA so far.

  • However, consider a class for people who are UCSC employees. They have an ID, but no GPA. Instead, they have a designation.

  • But both students and employees have all the people attributes!​

  • Enter inheritance!​

7

Inheritance

class people:

………… nm = “”

………… age = 0​

………… def __init__(self, name, age):

………………… self.​nm = name

​………………… self.age = age

……….. def intro(self):

…………………..print(“Hi, my name is ”, self.nm, “ and I’m ”, self.age, “ years old”)​

8

Inheritance

class student(people):

………… def __init__(self, name, age, gpa):

………………… self.​nm = name

​………………… self.age = age

………………… self.gpa​ = gpa

……….. def intro(self):

…………………..print(“Hi, my name is ”, self.nm, “ and I’m ”, self.age, “ years old, and my GPA is ”, gpa)

9

Inheritance

class employee(people):

………… def __init__(self, name, age, desig):

………………… self.​nm = name

​………………… self.age = age

………………… self.desig​ = desig

……….. def intro(self):

…………………..print(“Hi, my name is ”, self.nm, “ and I’m ”, self.age, “ years old, and my designation is ”, desig)

Object-oriented Programming

Show answer

Auto Play

Slide 1 / 9

SLIDE