Object Oriented Python - Open Computing Facility

Python OOP

Python Nitty Gritty

Object Oriented Python

Daniel Driver

E177-Advanced Matlab

April 21, 2015

Python OOP

Overview

1 Python OOP 2 Python Nitty Gritty

Python Nitty Gritty

Python OOP

Python OOP

Python Nitty Gritty

Python OOP

Python OOP

Defining a Class

Python Nitty Gritty

Classic-style Class

New-Style Class

DON'T DO THIS

ONLY USE THIS

Classic-style Class

introduced in 2.2

pre version 2.1

Type matches class name

Type always "instance" Removed in Python 3

Created by inheriting object class

definition:

definition:

class ExampleClass():

class ExampleClass(object):

Creation

Creation

>>>a=ExampleClass()

>>>a=ExampleClass()

python3 documentation

Python OOP

Adding a Method

Python Nitty Gritty

Basic Example with Methods Usage

class MethodBasicExample ( object ): def i n i t ( self , arg ): i f l e n ( arg )==1: s e l f . x=a r g [ 0 ] else : s e l f . x=0 def SquareX ( s e l f ): return s e l f . x s e l f . x def StoreY ( self , y ): s e l f . y=y def SquareYAddInput ( self , Input ): r e t u r n s e l f . y s e l f . y+I n p u t

init special method

called during construction used for initialization-create attributes and defaults any valid python code can go here

First input is object, convention to call "self" *arg is list of inputs

used for variable number of Inputs

>>>a=M e t h o d B a s i c E x a m p l e ( 3 ) >>>SqrX=a . SquareX ( ) >>>p r i n t ( SqrX ) 9 >>>SqY=a . S q u a r e Y A d d I n p u t ( 5 ) Traceback ( most recent c a l l l a s t ) :

F i l e " OOPBasics . py " , l i n e 7 0 , i n SqY=a . SquareYAddZ ( 5 ) AttributeError : ' MethodBasicExample ' object has no a t t r i b u t e ' SquareYAddZ '

>>>a . S t o r e Y ( 4 ) #s t o r e v a l u e i n s e l f . y >>>SqY=a . S q u a r e Y A d d I n p u t ( 5 ) >>>p r i n t ( SqY ) 21

Methods called with "dot" syntax

Attributes can be added at anytime

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download