본문 바로가기

프로그램언어/python

[Python] Class Operator Overloading

Why You Will Care: Operator Overloading

Later, we'll see that objects we implement ourselves with classes can pick and choose
from these categories arbitrarily. For instance, if you want to provide a new kind of
specialized sequence object that is consistent with built-in sequences, code a class that
overloads things like indexing, slicing, and concatenation:



class MySequence:
	def __init__(self, index ):
        '''
	       Constructor
        '''

	def __getitem__(self, index) :
	# called on self[index], for x in self, x in self

	def __getslice__(self, low, high) :
	# called on self[low:high]

	def __add__(self, other) :
	# called on self + other


and so on. You can also make the new object mutable or not, by selectively
implementing methods called for in-place change operations (e.g., __setitem__ is
called on self [index] =value assignments). Although this book isn't about C
integration, it's also possible to implement new objects in C, as C extension types. For
these, you fill in C function pointer slots to choose between number, sequence, and
mapping operation sets. Python built-in types are really precoded C extension types; like
Guido, you need to be aware of type categories when coding your own.