Skip to content

Instantly share code, notes, and snippets.

@hidsh
Created June 26, 2012 03:26
Show Gist options
  • Save hidsh/901204aff623bc72520d to your computer and use it in GitHub Desktop.
Save hidsh/901204aff623bc72520d to your computer and use it in GitHub Desktop.
python sample: operator overload
# sample: operator overload
class C1:
def __init__(self):
self.val_plus = 0
self.val_minus = 0
def __setattr__(self, attr, val):
if attr=='val_plus':
self.__dict__[attr] = val if val>0 else 0
elif attr=='val_minus':
self.__dict__[attr] = val if val<0 else 0
else:
raise AttributeError, 'no attribute: ' + attr
def print_values(o):
print '%d\t%d' % (o.val_plus, o.val_minus)
### test
if __name__ == '__main__':
o = C1()
print_values(o)
o.val_plus = 100
print_values(o)
o.val_plus = -100
print_values(o)
o.val_minus = 100
print_values(o)
o.val_minus = -100
print_values(o)
o.kkk = 100
### result
# >op_overload.py
# 0 0
# 100 0
# 0 0
# 0 0
# 0 -100
# Traceback (most recent call last):
# File "d:\shishido\py\test\op_overload.py", line 33, in <module>
# o.kkk = 100
# File "d:\shishido\py\test\op_overload.py", line 14, in __setattr__
# raise AttributeError, 'no attribute: ' + attr
# AttributeError: no attribute: kkk
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment