1 of 27

Classes: Object Oriented Programming

2 of 27

OBJECTS

  • Python supports many different kinds of data

1234 3.14159 "Hello" [1, 5, 7, 11, 13]

{"CA": "California", "MA": "Massachusetts"}

  • each is an object, and every object has:
    • a type
    • an internal data representation (primitive or composite)
    • a set of procedures for interaction with the object
  • an object is an instance of a type
    • 1234 is an instance of an int
    • "hello" is an instance of a string

3 of 27

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”

4 of 27

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

5 of 27

EXAMPLE:

[1,2,3,4] has type list

  • how are lists represented internally? linked list of cells

L =

  • how to manipulate lists?
    • L[i], L[i:j], +
    • len(), min(), max(), del(L[i])
    • L.append(),L.extend(),L.count(),L.index(), L.insert(),L.pop(),L.remove(),L.reverse(), L.sort()

1 -> 2 -> 3 -> 4 ->

6 of 27

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)

Implementing the class Using the class

7 of 27

HIERARCHIES

Animal

Cat

Rabbit

Person

  • parent class

(superclass)

  • child class

(subclass)

    • inherits all data and behaviors of parent class
    • add more info
    • add more behavior
    • override behavior

Student

Note: CompuCell3D Python modeling is done using basic hierarchies!

8 of 27

DEFINE YOUR OWN TYPES

  • use the class keyword to define a new type

class Coordinate(object):

#define attributes here

  • similar to def, indent code to indicate which statements are part of the class definition
  • the word object means that Coordinate is a Python object and inherits all its attributes
    • Coordinate is a subclass of object
    • object is a superclass of Coordinate

Implementing the class Using the class

9 of 27

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

10 of 27

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__

initialize some data attributes

class Coordinate(object):

def init (self, x, y):

self.x

=

x

self.y

=

y

Implementing the class Using the class

11 of 27

ACTUALLY CREATING AN INSTANCE OF A CLASS

c = Coordinate(3,4) origin = Coordinate(0,0) print(c.x) print(origin.x)

  • data attributes of an instance are called instance variables
  • don’t provide argument for self, Python does this automatically

Implementing the class Using the class

12 of 27

WHAT IS A METHOD?

  • procedural attribute, like a function that works only with a 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

13 of 27

DEFINE A METHOD FOR THE

Coordinate CLASS

class Coordinate(object): def init (self, x, y):

self.x = x self.y = y

def distance(self, other): x_diff_sq = (self.x-other.x)**2 y_diff_sq = (self.y-other.y)**2

return (x_diff_sq + y_diff_sq)**0.5

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

Implementing the class Using the class

14 of 27

HOW TO USE A METHOD

def distance(self, other):

# code here

Using the class:

  • conventional way

c = Coordinate(3,4) zero = Coordinate(0,0)

print(c.distance(zero))

  • equivalent to

c = Coordinate(3,4) zero = Coordinate(0,0)

print(Coordinate.distance(c, zero))

Implementing the class

Using the class

15 of 27

PRINT REPRESENTATION OF AN OBJECT

>>> c = Coordinate(3,4)

>>> print(c)

< main .Coordinate object at 0x7fa918510488>

  • 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

>>> print(c)

<3,4>

16 of 27

DEFINING YOUR OWN PRINT METHOD

class Coordinate(object):

def init (self, x, y):

self.x = x

self.y = y

def distance(self, other):

x_diff_sq = (self.x-other.x)**2 y_diff_sq = (self.y-other.y)**2

return (x_diff_sq + y_diff_sq)**0.5

def __str__(self):

return "<"+str(self.x)+","+str(self.y)+">"

Implementing the class Using the class

17 of 27

WRAPPING YOUR HEAD AROUND TYPES AND CLASSES

  • can ask for the type of an object instance

>>> c = Coordinate(3,4)

>>> print(c)

<3,4>

>>> print(type(c))

<class main .Coordinate>

  • this makes sense since

>>> print(Coordinate)

<class main .Coordinate>

>>> print(type(Coordinate))

<type 'type'>

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

>>> print(isinstance(c, Coordinate)) True

Implementing the class Using the class

18 of 27

SPECIAL OPERATORS

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

https://docs.python.org/3/reference/datamodel.html#basic-customization

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

add _(self, other)

self

+ other

sub (self, other)

self

- other

eq _(self, other)

self

== other

lt _(self, other)

self

< other

len (self)

len(self)

str (self)

... and others

print self

19 of 27

EXERCISE: COORDINATES

  • create a new type to represent a two numbers as coordinates
  • internal representation is two floats
    • “x” coordinate
    • “y” coordinate
  • interface a.k.a. methods a.k.a how to interact with

Coordinates objects

    • add, subtract
    • print representation
    • calculate distance to another instance
    • calculate relative coordinates with respect to another instance

20 of 27

THE POWER OF OBJECT ORIENTED PROGRAMMING

  • 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 of 27

Select Features for Computational Modeling and Scientific Computing

22 of 27

RANDOM NUMBERS

  • Library: random
  • Generates pseudo-random numbers according to various distributions

  • random.seed(a)
  • random.random()
  • random.uniform(a, b)
  • random.randint(a, b)
  • random.choice(seq)
  • random.gauss(mu, sigma)

 

Return random number in [0, 1) (uniform)

Return random integer in [a, b]

Return random element in sequence seq

Return random number in [a, b] (uniform)

Return random number with mean mu and

standard deviation sigma (Gaussian)

Think reproducibility!

23 of 27

TIME

  • Library: time
  • Provides functions related to time
  • Beginning of time according to your machine: “epoch”

  • time.gmtime(0)
  • time.time()
  • time.sleep(x)

Returns the epoch of your machine

Returns the number of seconds since the epoch

Pause the program for x seconds

24 of 27

MATH

  • Library: math
  • Provides functions for various mathematical calculations

  • math.pi, math.inf, math.nan
  • math.ceil(x), math.floor(x)
  • math.erf(x), math.exp(x), math.log(x)
  • math.factorial(x)
  • math.sqrt(x)
  • math.sin(x), math.cos(x), …

Useful constants!

Rounding functions

Error function, exponential, log…

As the name suggests…

Square root

Trig functions

25 of 27

STATISTICS

  • Library: statistics
  • Provides functions for basic statistical calculations

  • statistics.mean(seq)
  • statistics.median(seq)
  • statistics.quantiles(data, *, n)
  • statistics.stdev(seq)

Mean of a sequence

Median of a sequence

Standard deviation of a sequence

Returns boundaries of n quantiles of a sequence

26 of 27

EXERCISE: RANDOM WALK

  • Implement a 1-D random walk, where for each step a particle can move either up or down one unit with a probability of 0.05.
  • Simulate 100k steps, and calculate and report the position mean, standard deviation and RMS.
  • Report how much time the simulation requires to execute

27 of 27

Module Questionnaire

Please take a minute or two to let us know about your experience with this module by filling out the brief zoom survey

Feel free to provide additional comments and suggestions in the slack or by email to us as well (hfennel@iu.edu)

Funding Sources: NIH U24 EB028887, NSF 2120200, 2000281, 1720625

Previous Funding : NIH R01 GM122424