Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e876949

Browse files
committed
Initial revision
1 parent 04691fc commit e876949

7 files changed

Lines changed: 488 additions & 0 deletions

File tree

Demo/classes/Complex.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
# Complex numbers
2+
3+
4+
from math import sqrt
5+
6+
7+
def complex(re, im):
8+
return Complex().init(re, im)
9+
10+
11+
class Complex:
12+
13+
def init(self, re, im):
14+
self.re = float(re)
15+
self.im = float(im)
16+
return self
17+
18+
def __repr__(self):
19+
return 'complex' + `self.re, self.im`
20+
21+
def __cmp__(a, b):
22+
a = a.__abs__()
23+
b = b.__abs__()
24+
return (a > b) - (a < b)
25+
26+
def __float__(self):
27+
if self.im:
28+
raise ValueError, 'cannot convert complex to float'
29+
return float(self.re)
30+
31+
def __long__(self):
32+
return long(float(self))
33+
34+
def __int__(self):
35+
return int(float(self))
36+
37+
def __abs__(self):
38+
# XXX overflow?
39+
return sqrt(self.re*self.re + self.im*self.im)
40+
41+
def __add__(a, b):
42+
return complex(a.re + b.re, a.im + b.im)
43+
44+
def __sub__(a, b):
45+
return complex(a.re - b.re, a.im - b.im)
46+
47+
def __mul__(a, b):
48+
return complex(a.re*b.re - a.im*b.im, a.re*b.im + a.im*b.re)
49+
50+
def __div__(a, b):
51+
q = (b.re*b.re + b.im*b.im)
52+
re = (a.re*b.re + a.im*b.im) / q
53+
im = (a.im*b.re - b.im*a.re) / q
54+
return complex(re, im)
55+
56+
def __neg__(self):
57+
return complex(-self.re, -self.im)
58+
59+
60+
def test():
61+
a = complex(2, 0)
62+
b = complex(3, 4)
63+
print a, b
64+
print a+b, a-b, a*b, a/b
65+
print b+a, b-a, b*a, b/a
66+
i = complex(0, 1)
67+
print i, i*i, i*i*i, i*i*i*i
68+
j = complex(1, 1)
69+
print j, j*j, j*j*j, j*j*j*j
70+
print abs(j), abs(j*j), abs(j*j*j), abs(j*j*j*j)
71+
print i/-i
72+
73+
test()

Demo/classes/Dbm.py

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# A wrapper around the (optional) built-in class dbm, supporting keys
2+
# and values of almost any type instead of just string.
3+
# (Actually, this works only for keys and values that can be read back
4+
# correctly after being converted to a string.)
5+
6+
7+
def opendbm(filename, mode, perm):
8+
return Dbm().init(filename, mode, perm)
9+
10+
11+
class Dbm:
12+
13+
def init(self, filename, mode, perm):
14+
import dbm
15+
self.db = dbm.open(filename, mode, perm)
16+
return self
17+
18+
def __repr__(self):
19+
s = ''
20+
for key in self.keys():
21+
t = `key` + ': ' + `self[key]`
22+
if s: t = t + ', '
23+
s = s + t
24+
return '{' + s + '}'
25+
26+
def __len__(self):
27+
return len(self.db)
28+
29+
def __getitem__(self, key):
30+
return eval(self.db[`key`])
31+
32+
def __setitem__(self, key, value):
33+
self.db[`key`] = `value`
34+
35+
def __delitem__(self, key):
36+
del self.db[`key`]
37+
38+
def keys(self):
39+
res = []
40+
for key in self.db.keys():
41+
res.append(eval(key))
42+
return res
43+
44+
def has_key(self, key):
45+
return self.db.has_key(`key`)
46+
47+
48+
def test():
49+
d = opendbm('@dbm', 'rw', 0666)
50+
print d
51+
while 1:
52+
try:
53+
key = eval(raw_input('key: '))
54+
if d.has_key(key):
55+
value = d[key]
56+
print 'currently:', value
57+
value = eval(raw_input('value: '))
58+
if value == None:
59+
del d[key]
60+
else:
61+
d[key] = value
62+
except KeyboardInterrupt:
63+
print ''
64+
print d
65+
except EOFError:
66+
print '[eof]'
67+
break
68+
print d
69+
70+
71+
test()

Demo/classes/README

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
Examples of classes that implement special operators (see class.doc):
2+
3+
Complex.py Complex numbers
4+
Dbm.py Wrapper around built-in dbm, supporting arbitrary values
5+
Range.py Example of a generator: re-implement built-in range()
6+
Rat.py Rational numbers
7+
Vec.py A simple vector class
8+
9+
(For straightforward examples of basic class features, such as use of
10+
methods and inheritance, see the library code -- especially the window
11+
modules are full of them.)

Demo/classes/Range.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
# Example of a generator: re-implement the built-in range function
2+
# without actually constructing the list of values. (It turns out
3+
# that the built-in function is about 20 times faster -- that's why
4+
# it's built-in. :-)
5+
6+
7+
# Wrapper function to emulate the complicated range() arguments
8+
9+
def range(*a):
10+
if len(a) == 1:
11+
start, stop, step = 0, a[0], 1
12+
elif len(a) == 2:
13+
start, stop = a
14+
step = 1
15+
elif len(a) == 3:
16+
start, stop, step = a
17+
else:
18+
raise TypeError, 'range() needs 1-3 arguments'
19+
return Range().init(start, stop, step)
20+
21+
22+
# Class implementing a range object.
23+
# To the user the instances feel like immutable sequences
24+
# (and you can't concatenate or slice them)
25+
26+
class Range:
27+
28+
# initialization -- should be called only by range() above
29+
def init(self, start, stop, step):
30+
if step == 0:
31+
raise ValueError, 'range() called with zero step'
32+
self.start = start
33+
self.stop = stop
34+
self.step = step
35+
self.len = max(0, int((self.stop - self.start) / self.step))
36+
return self
37+
38+
# implement `x` and is also used by print x
39+
def __repr__(self):
40+
return 'range' + `self.start, self.stop, self.step`
41+
42+
# implement len(x)
43+
def __len__(self):
44+
return self.len
45+
46+
# implement x[i]
47+
def __getitem__(self, i):
48+
if 0 <= i < self.len:
49+
return self.start + self.step * i
50+
else:
51+
raise IndexError, 'range[i] index out of range'
52+
53+
54+
# Small test program
55+
56+
def test():
57+
import time, builtin
58+
print range(10), range(-10, 10), range(0, 10, 2)
59+
for i in range(100, -100, -10): print i,
60+
print
61+
t1 = time.millitimer()
62+
for i in range(1000):
63+
pass
64+
t2 = time.millitimer()
65+
for i in builtin.range(1000):
66+
pass
67+
t3 = time.millitimer()
68+
print t2-t1, 'msec (class)'
69+
print t3-t2, 'msec (built-in)'
70+
71+
72+
test()

Demo/classes/Rat.py

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# Rational numbers
2+
3+
4+
def rat(num, den):
5+
return Rat().init(num, den)
6+
7+
8+
def gcd(a, b):
9+
while b:
10+
a, b = b, a%b
11+
return a
12+
13+
14+
class Rat:
15+
16+
def init(self, num, den):
17+
if den == 0:
18+
raise ZeroDivisionError, 'rat(x, 0)'
19+
g = gcd(num, den)
20+
self.num = num/g
21+
self.den = den/g
22+
return self
23+
24+
def __repr__(self):
25+
return 'rat' + `self.num, self.den`
26+
27+
def __cmp__(a, b):
28+
c = a-b
29+
if c.num < 0:
30+
return -1
31+
if c.num > 0:
32+
return 1
33+
return 0
34+
35+
def __float__(self):
36+
return float(self.num) / float(self.den)
37+
38+
def __long__(self):
39+
return long(self.num) / long(self.den)
40+
41+
def __int__(self):
42+
return int(self.num / self.den)
43+
44+
def __coerce__(a, b):
45+
t = type(b)
46+
if t == type(0):
47+
return a, rat(b, 1)
48+
if t == type(0L):
49+
return a, rat(b, 1L)
50+
if t == type(0.0):
51+
return a.__float__(), b
52+
raise TypeError, 'Rat.__coerce__: bad other arg'
53+
54+
def __add__(a, b):
55+
return rat(a.num*b.den + b.num*a.den, a.den*b.den)
56+
57+
def __sub__(a, b):
58+
return rat(a.num*b.den - b.num*a.den, a.den*b.den)
59+
60+
def __mul__(a, b):
61+
return rat(a.num*b.num, a.den*b.den)
62+
63+
def __div__(a, b):
64+
return rat(a.num*b.den, a.den*b.num)
65+
66+
def __neg__(self):
67+
return rat(-self.num, self.den)
68+
69+
70+
def test():
71+
print rat(-1L, 1)
72+
print rat(1, -1)
73+
a = rat(1, 10)
74+
print int(a), long(a), float(a)
75+
b = rat(2, 5)
76+
l = [a+b, a-b, a*b, a/b]
77+
print l
78+
l.sort()
79+
print l
80+
print rat(0, 1)
81+
print rat(1, 0)
82+
print a+1
83+
print a+1L
84+
print a+1.0
85+
86+
test()

Demo/classes/Vec.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# A simple vector class
2+
3+
4+
def vec(*v):
5+
return apply(Vec().init, v)
6+
7+
8+
class Vec:
9+
10+
def init(self, *v):
11+
self.v = []
12+
for x in v:
13+
self.v.append(x)
14+
return self
15+
16+
17+
def fromlist(self, v):
18+
self.v = []
19+
if type(v) <> type([]):
20+
raise TypeError
21+
self.v = v[:]
22+
return self
23+
24+
25+
def __repr__(self):
26+
return 'vec(' + `self.v`[1:-1] + ')'
27+
28+
def __len__(self):
29+
return len(self.v)
30+
31+
def __getitem__(self, i):
32+
return self.v[i]
33+
34+
def __add__(a, b):
35+
# Element-wise addition
36+
v = []
37+
for i in range(len(a)):
38+
v.append(a[i] + b[i])
39+
return Vec().fromlist(v)
40+
41+
def __sub__(a, b):
42+
# Element-wise subtraction
43+
v = []
44+
for i in range(len(a)):
45+
v.append(a[i] - b[i])
46+
return Vec().fromlist(v)
47+
48+
def __mul__(self, scalar):
49+
# Multiply by scalar
50+
v = []
51+
for i in range(len(self.v)):
52+
v.append(self.v[i]*scalar)
53+
return Vec().fromlist(v)
54+
55+
56+
57+
def test():
58+
a = vec(1, 2, 3)
59+
b = vec(3, 2, 1)
60+
print a
61+
print b
62+
print a+b
63+
print a*3.0
64+
65+
test()

0 commit comments

Comments
 (0)