object-orientation, i · object-orientation, i gc3: grid computing competence center, university of...

23
GC3: Grid Computing Competence Center Object-orientation, I GC3: Grid Computing Competence Center, University of Zurich Sep. 11–12, 2013

Upload: others

Post on 16-Jul-2020

10 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Object-orientation, I · Object-orientation, I GC3: Grid Computing Competence Center, University of Zurich Sep. 11–12, 2013. What we shall see in this part How to define custom

GC3: Grid Computing Competence Center

Object-orientation, IGC3: Grid Computing Competence Center,University of Zurich

Sep. 11–12, 2013

Page 2: Object-orientation, I · Object-orientation, I GC3: Grid Computing Competence Center, University of Zurich Sep. 11–12, 2013. What we shall see in this part How to define custom

What we shall see in this part

How to define custom Python objects.

We shall use 2D vectors as examples.

GC3 Python training OOP 1 Sep. 11–12, 2013

Page 3: Object-orientation, I · Object-orientation, I GC3: Grid Computing Competence Center, University of Zurich Sep. 11–12, 2013. What we shall see in this part How to define custom

Recall: What is an object?

A Python object is a bundle of variables andfunctions.

What variable names and functions comprise anobject is defined by the object’s class.

From one class specification, many objects can beinstanciated. Different instances can assign differentvalues to the object variables.

Variables and functions in an instance are collectivelycalled instance attributes; functions are also termedinstance methods.

GC3 Python training OOP 1 Sep. 11–12, 2013

Page 4: Object-orientation, I · Object-orientation, I GC3: Grid Computing Competence Center, University of Zurich Sep. 11–12, 2013. What we shall see in this part How to define custom

Recall: What is a 2D vector?

A 2D vector is an element of the vector space R2.

Every 2D vector u is completely described by a pair ofreal coordinates 〈ux , uy〉. Two operations are definedon vectors:

vector addition: if w = u+ v, thenwx = ux + vx and wy = uy + vy.

scalar multiplication: if v = α · uwith α ∈ R, then vx = α · ux andvy = α · uy.

Reference: Images courtesy of http://jccc-mpg.wikidot.com/vectors, which see for precise

definitions and discussion of 2D vectors.

GC3 Python training OOP 1 Sep. 11–12, 2013

Page 5: Object-orientation, I · Object-orientation, I GC3: Grid Computing Competence Center, University of Zurich Sep. 11–12, 2013. What we shall see in this part How to define custom

A 2D vector in Python

class Vector(object):"""A 2D Vector."""def __init__(self, x, y):

self.x = xself.y = y

def add(self, other):return Vector(self.x+other.x,

self.y+other.y)def mul(self, scalar):

return Vector(scalar*self.x, scalar*self.y)def show(self):

return ("<%g,%g>" % (self.x, self.y))

This code defines a Pythonobject that implements a

2D vector.

Source code available at:

http://www.gc3.uzh.ch/edu/2013/python-march/vector.py

GC3 Python training OOP 1 Sep. 11–12, 2013

Page 6: Object-orientation, I · Object-orientation, I GC3: Grid Computing Competence Center, University of Zurich Sep. 11–12, 2013. What we shall see in this part How to define custom

What does Vector do?

We can create vectors byinitializing them with thetwo coordinates (x, y):

>>> u = Vector(1,0)>>> v = Vector(0,1)

The show method showsvector coordinates:

>>> u.show()’<1,0>’>>> v.show()’<0,1>’

The add methodimplements vectoraddition:

>>> w = u.add(v)>>> w.show()’<1,1>’

The mul methodimplements scalarmultiplication:

>>> v2 = v.mul(2)>>> v2.show()’<0,2>’

GC3 Python training OOP 1 Sep. 11–12, 2013

Page 7: Object-orientation, I · Object-orientation, I GC3: Grid Computing Competence Center, University of Zurich Sep. 11–12, 2013. What we shall see in this part How to define custom

User-defined classes, I

class Vector(object):"""A 2D Vector."""def __init__(self, x, y):

self.x = xself.y = y

def add(self, other):return Vector(self.x+other.x,

self.y+other.y)def mul(self, scalar):

return Vector(scalar*self.x, scalar*self.y)def show(self):

return ("<%g,%g>" % (self.x, self.y))

A class definition startswith the keyword class.

The class definition isindented relative to the

class statement.

GC3 Python training OOP 1 Sep. 11–12, 2013

Page 8: Object-orientation, I · Object-orientation, I GC3: Grid Computing Competence Center, University of Zurich Sep. 11–12, 2013. What we shall see in this part How to define custom

User-defined classes, II

class Vector (object) :

"""A 2D Vector."""def __init__(self, x, y):

self.x = xself.y = y

def add(self, other):return Vector(self.x+other.x,

self.y+other.y)def mul(self, scalar):

return Vector(scalar*self.x, scalar*self.y)def show(self):

return ("<%g,%g>" % (self.x, self.y))

This identifiesuser-defined classes.

(Do not leave it out oryou’ll get an “old-style”

class, which is deprecatedbehavior.)

GC3 Python training OOP 1 Sep. 11–12, 2013

Page 9: Object-orientation, I · Object-orientation, I GC3: Grid Computing Competence Center, University of Zurich Sep. 11–12, 2013. What we shall see in this part How to define custom

User-defined classes, II

class Vector(object):

"""A 2D Vector."""def __init__(self, x, y):

self.x = xself.y = y

def add(self, other):return Vector(self.x+other.x,

self.y+other.y)def mul(self, scalar):

return Vector(scalar*self.x, scalar*self.y)def show(self):

return ("<%g,%g>" % (self.x, self.y))

Classes can havedocstrings.

The content of a classdocstring will be shown as

help text for that class.

GC3 Python training OOP 1 Sep. 11–12, 2013

Page 10: Object-orientation, I · Object-orientation, I GC3: Grid Computing Competence Center, University of Zurich Sep. 11–12, 2013. What we shall see in this part How to define custom

User-defined classes, IV

class Vector(object):"""A 2D Vector."""

def init (self, x, y):

self.x = xself.y = y

def add(self, other):return Vector(self.x+other.x,

self.y+other.y)def mul(self, scalar):

return Vector(scalar*self.x, scalar*self.y)def show(self):

return ("<%g,%g>" % (self.x, self.y))

The def keywordintroduces a

method definition.

Every method must haveat least one argument,

named self.

GC3 Python training OOP 1 Sep. 11–12, 2013

Page 11: Object-orientation, I · Object-orientation, I GC3: Grid Computing Competence Center, University of Zurich Sep. 11–12, 2013. What we shall see in this part How to define custom

The self argument

Every method of a Python object always has selfas first argument.

However, you do not specify it when calling a method:it’s automatically inserted by Python:

>>> class ShowSelf(object):... def show(self):... print(self)...>>> x = ShowSelf() # construct instance>>> x.show() # ‘self’ automatically inserted!<__main__.ShowSelf object at 0x299e150>

The self name is a reference to the object instanceitself. You need to use self when accessing methodsor attributes of this instance.

GC3 Python training OOP 1 Sep. 11–12, 2013

Page 12: Object-orientation, I · Object-orientation, I GC3: Grid Computing Competence Center, University of Zurich Sep. 11–12, 2013. What we shall see in this part How to define custom

No access control

There are no “public”/“private”/etc. qualifiers forobject attributes.

Any code can create/read/overwrite/delete anyattribute on any object.

There are conventions, though:

– “protected” attributes: name

– “private” attributes: name

(But again, note that this is not enforced by thesystem in any way.)

GC3 Python training OOP 1 Sep. 11–12, 2013

Page 13: Object-orientation, I · Object-orientation, I GC3: Grid Computing Competence Center, University of Zurich Sep. 11–12, 2013. What we shall see in this part How to define custom

Name resolution rules, I

Within a function body, names are resolved according tothe LEGB rule:

L Local scope: any names defined in the currentfunction;

E Enclosing function scope: names defined inenclosing functions (outermost last);

G global scope: names defined in the toplevel ofthe enclosing module;

B Built-in names (i.e., Python’s builtinsmodule).

Any name that is not in one of the above scopes mustbe qualified.

So you have to write self.x to reference an attribute inthis instance, datetime.date to mean a class defined inmodule date, etc.

GC3 Python training OOP 1 Sep. 11–12, 2013

Page 14: Object-orientation, I · Object-orientation, I GC3: Grid Computing Competence Center, University of Zurich Sep. 11–12, 2013. What we shall see in this part How to define custom

Name resolution rules, II

import datetime as dt

def today():

td = dt.date.today()

return "today is " + td .isoformat()

def hey( name ):print("Hey " + name + "; " + today())

hey("you")

Unqualified namewithin a function:resolves to a local

variable.

GC3 Python training OOP 1 Sep. 11–12, 2013

Page 15: Object-orientation, I · Object-orientation, I GC3: Grid Computing Competence Center, University of Zurich Sep. 11–12, 2013. What we shall see in this part How to define custom

Name resolution rules, III

import datetime as dt

def today():td = dt.date.today()return "today is " + td.isoformat()

def hey(name):

print("Hey " + name + "; " + today ())

hey("you")

Unqualified name:since there is no local

variable by thatname, it resolves to amodule-level binding,

i.e., to the todayfunction defined

above.

GC3 Python training OOP 1 Sep. 11–12, 2013

Page 16: Object-orientation, I · Object-orientation, I GC3: Grid Computing Competence Center, University of Zurich Sep. 11–12, 2013. What we shall see in this part How to define custom

Name resolution rules, IV

import datetime as dt

def today():

td = dt .date.today()return "today is " + td.isoformat()

def hey(name):print("Hey " + name + "; " + today())

hey("you")

Unqualified name:resolves to the dt

name created atglobal scope by theimport statement.

GC3 Python training OOP 1 Sep. 11–12, 2013

Page 17: Object-orientation, I · Object-orientation, I GC3: Grid Computing Competence Center, University of Zurich Sep. 11–12, 2013. What we shall see in this part How to define custom

Name resolution rules, V

import datetime as dt

def today():

td = dt.date .today()return "today is " + td.isoformat()

def hey(name):print("Hey " + name + "; " + today())

hey("you")

Qualified name:instructs Python to

search the dateattribute within the

dt module.

GC3 Python training OOP 1 Sep. 11–12, 2013

Page 18: Object-orientation, I · Object-orientation, I GC3: Grid Computing Competence Center, University of Zurich Sep. 11–12, 2013. What we shall see in this part How to define custom

Name resolution rules, VI

import datetime as dt

def today():td = dt.date.today()

return "today is " + td.isoformat ()

def hey(name):print("Hey " + name + "; " + today())

hey("you")

Qualified name:Python searches theisoformat attributewithin the td object

instance.

GC3 Python training OOP 1 Sep. 11–12, 2013

Page 19: Object-orientation, I · Object-orientation, I GC3: Grid Computing Competence Center, University of Zurich Sep. 11–12, 2013. What we shall see in this part How to define custom

Name resolution rules, VI

class Vector(object):def __init__(self, x , y ):

self.x = xself.y = y

# ...

Unqualified name:resolves to a local

variable in scope offunction __init__.

GC3 Python training OOP 1 Sep. 11–12, 2013

Page 20: Object-orientation, I · Object-orientation, I GC3: Grid Computing Competence Center, University of Zurich Sep. 11–12, 2013. What we shall see in this part How to define custom

Name resolution rules, VII

class Vector(object):def __init__(self, x, y):

self.x = x

self.y = y

# ...

Qualified names:resolve to attributes

in object self.

(Actually,self.x = ... creates

the attribute x onself if it does not

exist yet.)

GC3 Python training OOP 1 Sep. 11–12, 2013

Page 21: Object-orientation, I · Object-orientation, I GC3: Grid Computing Competence Center, University of Zurich Sep. 11–12, 2013. What we shall see in this part How to define custom

Object initialization

class Vector(object):"""A 2D Vector."""

def init (self, x, y):

self.x = xself.y = y

def add(self, other):return Vector(self.x+other.x, self.y+other.y)

def mul(self, scalar):return Vector(scalar*self.x, scalar*self.y)

def show(self):return ("<%g,%g>" % (self.x, self.y))

The __init__ method hasa special meaning: it is

called when an instance iscreated.

GC3 Python training OOP 1 Sep. 11–12, 2013

Page 22: Object-orientation, I · Object-orientation, I GC3: Grid Computing Competence Center, University of Zurich Sep. 11–12, 2013. What we shall see in this part How to define custom

Constructors

The __init__ method is the object constructor. Itshould never return any value.

You never call __init__ directly, it is invoked byPython when a new object is created from the class:

# calls Vector. initv = Vector(0,1)

The arguments to __init__ are the arguments youshould supply when creating a class instance.

(Again, minus the self part which is automaticallyinserted by Python.)

GC3 Python training OOP 1 Sep. 11–12, 2013

Page 23: Object-orientation, I · Object-orientation, I GC3: Grid Computing Competence Center, University of Zurich Sep. 11–12, 2013. What we shall see in this part How to define custom

Exercise A: Add a new method norm the Vectorclass: if v is an instance of class Vector, then calling

v.norm() returns the norm√

v2x + v2

y of the associatedvector. (You will need the math standard module forcomputing square roots.)

Exercise B: Add a new method unit to the Vectorclass: if v is an instance of class Vector, then callingv.unit() returns the vector u having the samedirection as v but norm 1.

GC3 Python training OOP 1 Sep. 11–12, 2013