Docsity

Object Oriented Programming - Lecture Notes | CSCI 553, Study notes of Computer Systems Networking and Telecommunications

Partial preview of the text

Download Object Oriented Programming - Lecture Notes | CSCI 553 and more Study notes Computer Systems Networking and Telecommunications in PDF only on Docsity!

CSCI 553: Networking III

Unix Network Programming

Spring 2007

Object Oriented Programming More on Objects

Introduction

Previous lecture introduced basics of object-

oriented programming

This one goes a little further

As before, the ideas are (almost) universal, but

the form varies from language to language

Overloading

Operators

 The expression "a + b" is “just” a

shorthand for add(a, b)

 Or, if a is an object, for a.add(b)

 But since people might actually want

to use the name add, Python spells

this method add

 Defining it is an example of

operator overloading

 If a class defines a method add,

it is called whenever something is

+'d to the object

 I.e., x + y calls x.add(y)

class Recent(object): def add(self, item): self.items.append(item) self.items = self.items[-self.number:] return self if name == 'main': history = Recent() for era in ['Permian', 'Trassic', 'Jurassic', 'Cretaceous', 'Tertiary']: history = history + era print len(history), history 1 ['Permian'] 2 ['Permian', 'Trassic'] 3 ['Permian', 'Trassic', 'Jurassic'] 3 ['Trassic', 'Jurassic', 'Cretaceous'] 3 ['Jurassic', 'Cretaceous', 'Tertiary']

Commutativity

2 + x and x + 2 don't always do the same thing

Matrix multiplication

Classes can define right-hand versions of

operators, e.g., radd instead of add

If the object on the left has an add

method, call that

Otherwise, if the object on the right has an

radd method, call that

Otherwise, try Python's built-ins

Example: Sparse Vector

 A vector is sparse if most of its entries are zero

 Use a dictionary to record non-zero values and their indices

No point padding eleven actual values with nine million

zeroes

Overload operators to make the object look like a “real”

vector:

 Addition: create a new vector with a non-zero value wherever

either operand had a non-zero value

 Dot product: add up products of matching non-zero values

 Length: return one more than the index of the largest non-

zero value

 “One more” to be consistent with Python's lists

How Long is a Sparse Vector?

 What is the length of v after the following operations?

v = SparseVector() # all values initialized to 0. v[27] = 1.0 # length is now 28 v[43] = 1.0 # length is now 44 v[43] = 0.0 # is the length still 44, or 28?

 This isn't really a programming question

 “Largest current index” and “largest index ever seen” can

both be implemented

 The latter is easy, so we'll use that

Dot Product

 (^) The other object (on the right side of "*") is usually called other  (^) No reason to insist that it be a sparse vector  (^) Could equally well be a list of values  (^) So loop over our indices, and multiply by corresponding values in other object  (^) Any index not encountered in this loop doesn't matter, since it corresponds to something that's zero  (^) And make rmul = mul do the same thing as rmul def mul(self, other): '''Calculate dot product of a sparse vector with something else.''' result = 0. for k in self.data: result += self.data[k] * other[k] return result def rmul(self, other): return self.mul(other)

Addition

 Trickier than multiplication:

result is non-zero wherever

either argument is non-zero

 Don't want to loop over all

the zeroes of either

argument

 Solution: if the other object

is a sparse vector, cheat

 I.e., reach inside it, and

rely on details of its

implementation

def add(self, other): '''Add something to a sparse vector.'''

Initialize result with all non-zero values from this vector.

result = SparseVector() result.data.update(self.data)

If the other object is also a sparse vector, add non-zero values.

if isinstance(other, SparseVector): for k in other.data: result[k] = result[k] + other[k]

Otherwise, use brute force.

else: for i in range(len(other)): result[i] = result[i] + other[i] return result

Right-hand add does the same thing as left-hand add.

radd = add

Static Data Members

 Sometimes want to

share data between

all instances of a

class

 Constants, a

count of the

number of class

instances created,

etc.

 Any data members

defined inside the

class block belong to

the class as a whole

class Counter(object): num = 0 # Number of Counter objects created. def init(self, name): Counter.num += 1 self.name = name if name == 'main': print 'initial count', Counter.num first = Counter('first') print 'after creating first object', Counter.num second = Counter('second') print 'after creating second object', Counter.num initial count 0 after creating first object 1 after creating second object 2

Static Methods

 (^) Can also create static methods  (^) Just like a function, but put inside the class definition for clarity  (^) Define the method without the self parameter  (^) Since it isn't tied to any particular instance of the class  (^) Put @staticmethod in front of it  (^) A decorator  (^) Powerful, but beyond the scope of this course class Experiment(object): already_done = {} @staticmethod def get_results(name, *params): if name in Experiment.already_done: return Experiment.already_done[name] exp = Experiment(name, *params) exp.run() Experiment.already_done[name] = exp return exp def init(self, name, *params): self.name = name self.params = params def run(self):

...

if name == 'main': first = Experiment.get_results('anti-gravity') second = Experiment.get_results('time travel') third = Experiment.get_results('anti-gravity') print 'first ', id(first) print 'second', id(second) print 'third ', id(third) first 5120204 second 5120396 third 5120204

The Singleton Pattern

 Problem: want to ensure that there's only ever one instance of a

particular class

 E.g. the controller for a radio telescope antenna

 Considerations:

 There must be exactly one instance of the class

 All objects that use the class must have access to that instance

 Solution:

 Create objects by calling a function instead of the class's

constructor

 Have the function store a reference to the first object it creates

 Have it return that same object on every subsequent call

Singleton Implementation

class AntennaClass(object): '''Singleton that controls a radio telescope.'''

The unique instance of the class.

instance = None

The constructor fails if an instance already exists.

def init(self, max_rotation): assert AntennaClass.instance is None, 'Trying to create a second instance!' self.max_rotation = max_rotation AntennaClass.instance = self

Make the creation function look like a class constructor.

def Antenna(max_rotation): '''Create and store an AntennaClass instance, or return the one that has already been created.''' if AntennaClass.instance: return AntennaClass.instance return AntennaClass(max_rotation)

The Visitor Pattern

 Problem: want an easy way to walk around a complex structure

 E.g. visit each value in a list of lists of lists exactly once

 Considerations:

 Many different operations may need to be performed

 Structure is complex enough that visiting elements is error-prone

 The types of objects in the structure, and the ways they are

connected, are fixed

 Solution:

 Create a class that knows how to get to each value in turn

 Give it an empty method that is called once for each value

 Users derive from this class and fill in the method

 An all-in-one version of the framework shown earlier

Visitor Implementation

class NestedListVisitor(object): '''Visit each element in a list of nested lists.''' def init(self, data): '''Construct, but do not run.''' assert type(data) is list, 'Only works on lists!' self.data = data def run(self): '''Iterate over all values.''' self.recurse(self.data) def recurse(self, current): '''Loop over a particular list or sub-list (not meant to be called by users).''' if type(current) is list: for v in current: self.recurse(v) else: self.visit(current) def visit(self, value): '''Users should fill this method in.''' pass