nick34992 of Python
2/2/2017 - 7:15 AM

Examples of Python Magic Methods

Examples of Python Magic Methods

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
FileName: magic_methods.py
Author: nick3499
Created: Fri Jan 20 2017
Python Version: 3.5
'''

x = 1
y = 2
z = 1,2

print('magic method examples\nif x = 1, y = 2, z = 1,2')
print('x + y   ... x.__add__(y) =', x.__add__(y))
print('x - y   ... x.__sub__(y) =', x.__sub__(y))
print('x == y  ... x.__eq__(y) =', x.__eq__(y))
print('x >= y  ... x.__ge__(y) =', x.__ge__(y))
print('x <= y  ... x.__le__(y) =', x.__le__(y))
print('x > y   ... x.__gt__(y) =', x.__gt__(y))
print('x < y   ... x.__lt__(y) =', x.__lt__(y))
print('x % y   ... x.__mod__(y) =', x.__mod__(y))
print('x * y   ... x.__mul__(y) =', x.__mul__(y))
print('x != y  ... x.__ne__(y) =', x.__ne__(y))
print('x       ... __hash__(x) =', hash(x))
print('z[0]    ... z.__getitem__(0)', z.__getitem__(0))
print('int(x)  ...  __int__(x)', x.__int__)
print('neg(x)  ...  __neg__(x)', x.__neg__)
print('repr(x) ... __repr__(x)', x.__repr__)
print('str(x)  ... x.__str__', x.__str__)
print('for a in z', z.__iter__())