























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!
























Object Oriented Programming More on Objects
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']
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?
(^) 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)
def add(self, other): '''Add something to a sparse vector.'''
result = SparseVector() result.data.update(self.data)
if isinstance(other, SparseVector): for k in other.data: result[k] = result[k] + other[k]
else: for i in range(len(other)): result[i] = result[i] + other[i] return result
radd = add
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
(^) 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
class AntennaClass(object): '''Singleton that controls a radio telescope.'''
instance = None
def init(self, max_rotation): assert AntennaClass.instance is None, 'Trying to create a second instance!' self.max_rotation = max_rotation AntennaClass.instance = self
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)
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