-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoperator_classes.py
More file actions
48 lines (41 loc) · 966 Bytes
/
Copy pathoperator_classes.py
File metadata and controls
48 lines (41 loc) · 966 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2008 Doug Hellmann All rights reserved.
#
"""
不仅仅适用于内置类型 还适用于用户类型
"""
__version__ = "$Id$"
#end_pymotw_header
from operator import *
class MyObj(object):
"""Example for operator overloading"""
def __init__(self, val):
super(MyObj, self).__init__()
self.val = val
return
def __str__(self):
return 'MyObj(%s)' % self.val
def __lt__(self, other):
"""compare for less-than"""
print 'Testing %s < %s' % (self, other)
return self.val < other.val
def __add__(self, other):
"""add values"""
print 'Adding %s + %s' % (self, other)
return MyObj(self.val + other.val)
a = MyObj(1)
b = MyObj(2)
print 'Comparison:'
print lt(a, b)
# Comparison:
# Testing MyObj(1) < MyObj(2)
# True
#
print '\nArithmetic:'
print add(a, b)
# Arithmetic:
# Adding MyObj(1) + MyObj(2)
# MyObj(3)
#