Clean Code hochulshin.com

Python - special methods

2016-04-11

Python class predefines some special methods.

Special methods

  • Instance creation and destruction: new, init, del
  • String/bytes representation: repr, str, format, bytes
  • Conversion to number: abs, bool, complex, int, float, hash, index
  • Emulating collections: len, getitem, setitem, delitem, contains
  • Iteration: iter, reversed, next
  • Emulating callables: call
  • Context management: enter, exit
  • Attribute management: getattr, getattribute, setattr, delattr, dir
  • Attribute descriptors: get, set, delete
  • Class services: prepare, instancecheck, subclasscheck

Special methods for operators

  • Unary numeric operators: neg -, pos +, abs abs()
  • Rich comparison operators: lt >, le <=, eq ==, ne !=, gt >, ge >=
  • Arithmetic operators: add +, sub -, mul *, truediv /, floordiv //, mod %, divmod divmod() , pow ** or pow(), round round()
  • Reversed arithmetic operators: radd, rsub, rmul, rtruediv, rfloordiv, rmod, rdivmod, rpow
  • Augmented assignment arithmetic operators: iadd, isub, imul, itruediv, ifloordiv, imod, ipow
  • Bitwise operators: invert ~, lshift «, rshift », and &, or , xor ^
  • Reversed bitwise operators: rlshift, rrshift, rand, rxor, ror
  • Augmented assignment bitwise operators: ilshift, irshift, iand, ixor, ior

Example of redefining special methods

You could override or define them in your classes as below. This exmple came from the book, “fluent python”.

from math import hypot 

class Vector:
	def __init__(self, x = 0, y = 0):
		self.x = x
		self.y = y
	def __repr__(self):
		return 'Vector(%r, %r)' % (self.x, self.y)
	def __abs__(self):
		return hypot(self.x, self.y)
	def __bool__(self):
		return bool(abs(self))
	def __add__(self, other):
		x = self.x + other.x
		y = self.y + other.y
		return Vector(x, y)
	def __mul__(self, scalar):
		return Vector(self.x*scalar, self.y*scalar)
	def __str__(self):
		return "Vector(%r, %r)" % (self.x, self.y)

Test code

You could test them as follows.

#__init__ invoked
v1 = Vector()
v2 = Vector(3, 4)
#__str__ invoked
print str(v2) # Vector(3, 4)
#__add__ invoked
v3 = v1 + v2 
print str(v3) # Vector(3, 4)
#__abs__ invoked
print abs(v3) # 5.0
#__mul__ invoked
v4 = v3*3
print str(v4) # Vector(9, 12)
#__bool__ invoked
print bool(v4) #true

Previous : Python - xml

Comments