PyBc/AdvancedPython: PyBC_S9_simple_num.py

File PyBC_S9_simple_num.py, 1.8 KB (added by scopatz, 8 months ago)

Advanced Python Simple Numbers

Line 
1class SimpleNum():
2        "A Simple Number in a Simple Metric Space."
3        def __init__(self, x):
4                if int(x) == 0:
5                        self.val = 0
6                else:
7                        self.val = 1
8
9        def __str__(self):
10                return str(self.val)
11
12        def __int__(self):
13                return int(self.val)
14
15        def __float__(self):
16                return float(self.val)
17
18        def __add__(self, y):
19                if self.val == 1:
20                        return SimpleNum(1)
21                elif int(y) == 0:
22                        return SimpleNum(0)
23                else: 
24                        return SimpleNum(1)
25                       
26        #__add__() could be more concisely written as:
27        #def __add__(self, y):
28        #       return SimpleNum(self.val + SimpleNum(y).val)
29        #where __init__() takes care of the details...
30
31        def __radd__(self, y):
32                "Addition is communative! Here, at least..."
33                return self.__add__(y)
34
35        def __sub__(self, y):
36                y = SimpleNum(y)
37                return SimpleNum(self.val - y.val)
38
39        def __rsub__(self, y):
40                "Since we have no negative numbers, subtraction is also communative!"
41                return self.__sub__(self, y)
42
43        def __mul__(self, y):
44                y = SimpleNum(y)
45                return SimpleNum(self.val * y.val)
46
47        def __rmul__(self, y):
48                if isinstance(y, SimpleNum):
49                        return self.__mul__(y)
50                else:
51                        return NotImplemented
52
53#Define some SimpleNums
54i = SimpleNum(0)
55j = SimpleNum(37.0)
56k = SimpleNum(True)
57
58print("i = {0}".format(i)) 
59print("j = {0}".format(j)) 
60print("k = {0}".format(k)) 
61print("")
62
63#Define SimpleNums from additive operations
64a = i + 0
65b = 0 + j
66c = a + b
67
68print("a = {0}".format(a)) 
69print("b = {0}".format(b)) 
70print("c = {0}".format(c)) 
71print("")
72
73#Define SimpleNums from subtraction
74p = a - b
75q = k - (c + 1) 
76r = k - (c - 1) 
77
78print("p = {0}".format(p)) 
79print("q = {0}".format(q)) 
80print("r = {0}".format(r)) 
81print("")
82
83#Define SimpleNums from multiplication
84e = j * b
85f = q * True
86g = c * 3
87print("e = {0}".format(e)) 
88print("f = {0}".format(f)) 
89print("g = {0}".format(g)) 
90print("")
91
92h = 50.0 * k
93print("h = {0}".format(h))