0% found this document useful (0 votes)
2 views46 pages

python lec3

session3 from route

Uploaded by

harithmsylhy3
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)
2 views46 pages

python lec3

session3 from route

Uploaded by

harithmsylhy3
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/ 46

Introduction to

PYTHONDemystifying the World of Artificial


Intelligence and Exploring Its Potential

1
Artificial Intelligence
OBJECT ORIENTED
PROGRAMMING (OOP)

• EVERYTHING IN PYTHON IS AN OBJECT (and has a type)


• can create new objects of some type
• can manipulate objects
• can destroy objects
▪ explicitly using del or just “forget” about them
▪ python system will reclaim destroyed or inaccessible objects – called
“garbage collection”

2
Artificial Intelligence
WHAT ARE OBJECTS?

• objects are a data abstraction that captures…


1. an internal representation
▪ through data attributes
2. an interface for interacting with object
▪ through methods (aka procedures/functions)
▪ defines behaviors but hides implementation

3
Artificial Intelligence
EXAMPLE: [1,2,3,4] has type list

• how are lists represented internally? linked list of cells

• how to manipulate lists?

4
Artificial Intelligence
EXAMPLE: [1,2,3,4] has type list

• how are lists represented internally? linked list of cells

• how to manipulate lists?


• internal representation should be private
• correct behavior may be compromised
if you manipulate internal
representation directly

5
Artificial Intelligence
ADVANTAGES OF OOP

• bundle data into packages together with procedures that work on them
through well-defined interfaces
• divide-and-conquer development
▪ implement and test behavior of each class separately
▪ increased modularity reduces complexity
• classes make it easy to reuse code
▪ many Python modules define new classes
▪ each class has a separate environment (no collision on function names)
• inheritance allows subclasses to redefine or extend a selected subset of a
superclass’ behavior

6
Artificial Intelligence
CREATING AND USING YOUR
OWN TYPES WITH CLASSES
• make a distinction between creating a class and using an instance of the
class
▪ creating the class involves
▪ defining the class name
▪ defining class attributes
▪ for example, someone wrote code to implement a list class
• using the class involves
▪ creating new instances of objects
▪ doing operations on the instances
▪ for example, L=[1,2] and len(L)

7
Artificial Intelligence
DEFINE YOUR OWN TYPES
• use the class keyword to define a new type

Name/type
• similar to def, indent code to indicate
Class
which statements are part of the class
definition
Class definition
parent
• the word object means that Coordinate is
a Python object and inherits all its
attributes (inheritance next lecture)
▪ Coordinate is a subclass of object
▪ object is a superclass of Coordinate

8
Artificial Intelligence
WHAT ARE ATTRIBUTES?

• data and procedures that “belong” to the class


• data attributes
▪ think of data as other objects that make up the class
▪ for example, a coordinate is made up of two numbers
• methods (procedural attributes)
▪ think of methods as functions that only work with this class
▪ how to interact with the object
▪ for example, you can define a distance between two coordinate
objects but there is no meaning to a distance between two list objects.

9
Artificial Intelligence
DEFINING HOW TO CREATE AN
INSTANCE OF A CLASS
• first have to define how to create an instance of object
• use a special method called __init__ to initialize some data attributes

special method to create an


instance is double underscore what data initializes a
Coordinate object

parameter to refer to an
instance of the class

two data attributes for


every Coordinate object
10
Artificial Intelligence
ACTUALLY, CREATING AN
INSTANCE OF A CLASS

create a new object of type


Coordinate and pass in 3 and 4
to the _init_

use the dot to access an attribute of instance c

• data attributes of an instance are called instance variables


• don’t provide argument for self, Python does this automatically

11
Artificial Intelligence
WHAT IS A METHOD?

• procedural attribute, like a function that works only with this class
• Python always passes the object as the first argument
▪ convention is to use self as the name of the first argument of all
methods
• the “.” operator is used to access any attribute
▪ a data attribute of an object
▪ a method of an object

12
Artificial Intelligence
DEFINE A METHOD FOR THE
Coordinate CLASS

use it to refer to any instance

another parameter to method

dot notation to access data

• other than self and dot notation, methods behave just like functions (take params, do operations, return)

13
Artificial Intelligence
HOW TO USE A METHOD Method def

• Using the class:


⮚ conventional way ⮚ equivalent to

parameters not including


self (self is implied to be c) name of class name of parameters, including an
object to call name of method object to call the method on,
method on method representing self

14
Artificial Intelligence
PRINT REPRESENTATION OF
AN OBJECT

• uninformative print representation by default


• define a __str__ method for a class
• Python calls the __str__ method when used with print on your class object
• you choose what it does! Say that when we print a Coordinate object, want to show

15
Artificial Intelligence
DEFINING YOUR OWN PRINT
METHOD

16
Artificial Intelligence
WRAPPING YOUR HEAD
AROUND TYPES AND CLASSES

• can ask for the type of an object instance

return of the _str_ method

the type of object c is a class Coordinate

17
Artificial Intelligence
WRAPPING YOUR HEAD
AROUND TYPES AND CLASSES
• can ask for the type of an object instance

• this makes sense since

a Coordinate is a class

a Coordinate class is a type of object

18
Artificial Intelligence
WRAPPING YOUR HEAD
AROUND TYPES AND CLASSES
• can ask for the type of an object instance • this makes sense since

• use isinstance() to check if an object is a Coordinate

19
Artificial Intelligence
SPECIAL OPERATORS

• +, -, ==, <, >, len(), print, and many others


• like print, can override these to work with your class
• define them with double underscores before/after

20
Artificial Intelligence
THE POWER OF OOP

• bundle together objects that share


▪ common attributes and
▪ procedures that operate on those attributes
• use abstraction to make a distinction between how to implement an object
vs how to use the object
• build layers of object abstractions that inherit behaviors from other classes
of objects
• create our own classes of objects on top of Python’s basic classes

21
Artificial Intelligence
• write code from two different perspectives

IMPLEMENTING USING THE


THE CLASS CLASS

Implementing a new object type with a


class Using the new object type in code
• define the class • create instances of the object type
• define data attributes (WHAT IS • do operations with them
the object)
• define methods (HOW TO use the
object)

22
Artificial Intelligence
CLASS DEFINITION INSTANCE
OF AN OBJECT TYPE OF A CLASS
• class name is the type • instance is one specific object
class Coordinate(object) coord = Coordinate(1,2)
• class is defined generically • data attribute values vary between instances
▪ use self to refer to some instance while c1 = Coordinate(1,2)
defining the class.
c2 = Coordinate(3,4)
(self.x – self.y)**2
• c1 and c2 have different data attribute values
▪ self is a parameter to methods in class c1.x and c2.x because they are different objects
definition
• instance has the structure of the class
• class defines data and methods common across
all instances

23
Artificial Intelligence
WHY USE OOP AND
CLASSES OF OBJECTS?
• mimic real life
• group different objects part of the same type

24
Artificial Intelligence
WHY USE OOP AND
CLASSES OF OBJECTS?
• mimic real life
• group different objects part of the same type

25
Artificial Intelligence
GROUPS OF OBJECTS HAVE
ATTRIBUTES (RECAP)
• data attributes
▪ how can you represent your object with data?
▪ what it is
▪ for a coordinate: x and y values
▪ for an animal: age, name
• procedural attributes (behavior/operations/methods)
▪ how can someone interact with the object?
▪ what it does
▪ for a coordinate: find distance between two
▪ for an animal: make a sound

26
Artificial Intelligence
HOW TO DEFINE A CLASS (RECAP)

27
Artificial Intelligence
GETTER AND SETTER METHODS

• getters and setters should be used outside of class to access data attributes

28
Artificial Intelligence
AN INSTANCE and
DOT NOTATION (RECAP)
• instantiation creates an instance of an object
a = Animal(3)

• dot notation used to access attributes (data and methods) though it is


better to use getters and setters to access data attributes
a.age -- access data attribute
allowed, but not recommended

- access method
a.get_age() - best to use getters and setters

29
Artificial Intelligence
AN INSTANCE and
DOT NOTATION (RECAP)
• author of class definition may change
data attribute variable names

• if you are accessing data attributes outside the class and class definition changes, may get errors

• outside of class, use getters and setters instead


• use a.get_age() NOT a.age
▪ good style
▪ easy to maintain code
▪ prevents bugs

30
Artificial Intelligence
PYTHON NOT GREAT AT
INFORMATION HIDING

• allows you to access data from outside class definition


print(a.age)
• allows you to write to data from outside class definition
a.age = 'infinite'
• allows you to create data attributes for an instance from outside class definition
a.size = "tiny“

• it’s not good style to do any of these!

31
Artificial Intelligence
DEFAULT ARGUMENTS

• default arguments for formal parameters are used if no actual argument is given
def set_name(self, newname=""):
self.name = newname
• default argument used here
a = Animal(3)
a.set_name()
print(a.get_name())
• argument passed in is used here
a = Animal(3)
a.set_name("fluffy")
print(a.get_name())

32
Artificial Intelligence
HIERARCHIES

People
Student

Cat Rabbit

33
Artificial Intelligence
HIERARCHIES
Animal
• parent class (superclass)
• child class (subclass)
• inherits all data and behaviors of
parent class Person Cat Rabbit
• add more info
• add more behavior
• override behavior
Student

34
Artificial Intelligence
INHERITANCE:
PARENT CLASS

35
Artificial Intelligence
INHERITANCE: inherits all attributes of
Animal:

PARENT CLASS _init__()


age, name
get_age(), get_name()
set_age(), set_name()
_str_()

add new functionality via


speak method

overrides _str_

36
Artificial Intelligence
INHERITANCE:
PARENT CLASS

• add new functionality with speak()


▪ instance of type Cat can be called with new methods
▪ instance of type Animal throws error if called with Cat’s new method

• __init__ is not missing, uses the Animal version

37
Artificial Intelligence
WHICH METHOD TO USE?

• subclass can have methods with same name as superclass


• for an instance of a class, look for a method name in current class definition
• if not found, look for method name up the hierarchy (in parent, then grandparent, and
so on)
• use first method up the hierarchy that you found with that method name

38
Artificial Intelligence
EX.

39
Artificial Intelligence
EX.

40
Artificial Intelligence
CLASS VARIABLES AND THE
Rabbit SUBCLASS
• class variables and their values are shared between all instances of a class

• tag used to give unique id to each new rabbit instance

41
Artificial Intelligence
Rabbit GETTER METHODS

42
Artificial Intelligence
WORKING WITH YOUR OWN TYPES

• define + operator between two Rabbit instances


▪ define what something like this does: r4 = r1 + r2 where r1 and r2 are Rabbit
instances
▪ r4 is a new Rabbit instance with age 0
▪ r4 has self as one parent and other as the other parent
▪ in __init__, parent1 and parent2 are of type Rabbit

43
Artificial Intelligence
SPECIAL METHOD TO
COMPARE TWO Rabbits
• decide that two rabbits are equal if they have the same two parents

• compare ids of parents since ids are unique (due to class var)
• note you can’t compare objects directly
▪ for ex. with self.parent1 == other.parent1
▪ this calls the __eq__ method over and over until call it on None and gives an AttributeError when it
tries to do None.parent1

44
Artificial Intelligence
OBJECT ORIENTED
PROGRAMMING

• create your own collections of data


• organize information
• division of work
• access information in a consistent manner add layers of complexity
• like functions, classes are a mechanism for decomposition and abstraction in
programming

45
Artificial Intelligence
THANK
YOU!
Any Question!

46

You might also like