faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

4 of 7 people (57%) answered Yes
Recently 2 of 4 people (50%) answered Yes

Entry

Little examples of OO code in Python

Jul 5th, 2000 09:59
Nathan Wallace, Hans Nowak, Snippet 73, Christian Tismer


"""
Packages: oop
"""
""" 
> > This a very nice use of classes. I'd like to use this in my
> > Python class.
> 
> Use it! BTW I will give a python course on Wednesday,
> so I was looking for good, small OO examples. See also
> the little sorter framework:
>   http://www.dejanews.com/getdoc.xp?AN=444572294
> 
> I think it would be nice to collect some little
> OO examples. Do you have some more examples?
Now, half baked units, maybe. Started sometimes, never ended.
units.py
-------------------------------------------------------------
"""
# MKSI
# rules to make this a little efficient:
# unit dicts are assigned around and never changed
# it could also make sense to use tuples instead
import string
from math import sqrt
#class UnitError : pass
UnitError = "UnitError"
class UnitType :
 def __init__(self, unitdict) :
  if type(unitdict) == type('') :
   unitdict = {string.strip(unitdict):1}
  self.unit = unitdict
 def __add__(self, other) :
  if self.unit == other.unit :
   return self
  raise UnitError, "cannot add %s and %s" %(`self`,`other`)
 def __sub__(self, other) :
  if self.unit == other.unit :
   return self
  raise UnitError, "cannot sub %s and %s" %(`self`,`other`)
 def __mul__(self, other) :
  return self.calc_unit(other)
 def __div__(self, other) :
  return self.calc_unit_inv(other)
 def __repr__(self) :
  lis = []
  for key, pow in self.unit.items() :
   lis.append(pow, key)
  lis.sort()
  lis.reverse()
  pos = filter(lambda x:x[0]>0, lis)
  neg = lis[len(pos):]
  res = ""
  for pow, key in pos :
   res = res + " " + key
   if pow != 1 :
    res = res + "^" + `pow`
  if neg:
   negres = ""
   for pow, key in neg :
    negres = negres + " " +key
    if pow != -1 :
     negres = negres + "^" + `-pow`
   if len(neg) > 1:
    negres = "(%s)" % negres
   res = res + "/" + string.strip(negres)
  return string.strip(res)
 def sqrt(self) :
  newdict = self.unit.copy()
  for key, pow in newdict.items() :
   if pow % 2 : pow = pow/2.0
   else : pow = pow/2
   newdict[key] = pow
  return self.__class__(newdict)
 def calc_unit(self, other) :
  newdict = self.unit.copy()
  for key, pow in other.unit.items() :
   if newdict.has_key(key) :
    newpow = newdict[key] + pow
    if newpow : newdict[key] = newpow
    else : del newdict[key]
   else :
    newdict[key] = pow
  return self.__class__(newdict)
 def calc_unit_inv(self, other) :
  newdict = self.unit.copy()
  for key, pow in other.unit.items() :
   if newdict.has_key(key) :
    newpow = newdict[key] - pow
    if newpow : newdict[key] = newpow
    else : del newdict[key]
   else :
    newdict[key] = -pow
  return self.__class__(newdict)
class MeasurementType:
 def __init__(self, value, unit) :
  self.value = value
  self.unit = unit
 def __repr__(self) :
  return `self.value`+ " " + str(self.unit)
 def __add__(self, other) :
  return self.__class__(self.value+other.value, self.unit+other.unit)
 def __sub__(self, other) :
  return self.__class__(self.value-other.value, self.unit-other.unit)
 def __mul__(self, other) :
  return self.__class__(self.value*other.value, self.unit*other.unit)
 def __div__(self, other) :
  denom = other.value
  if type(denom)==type(1):
   denom=float(denom)
  return self.__class__(self.value/denom, self.unit/other.unit)
 def sqrt(self) :
  return self.__class__(sqrt(self.value), self.unit.sqrt())
meter  = UnitType("m")
second = UnitType("s")
mass   = UnitType("g")
speed  = meter/second
MT = MeasurementType # :-)
print MT(2, second) * MT(5, speed)
# example giving 10 m