Python class operator overloading Maya API docs demystified for Python users
Feb 13

I was curious if it was possible to overload the [] operators twice in a row to imitate a matrix while still using a single array. Someone gave me an example to go off of and here is a working example of how to make a flatMatrix class in python.

Try this in the Python script tab in Maya:

class SubItem:

	def __init__(self, parent, idx):
		self.parent = parent
		self.idx = idx

	def __repr__(self):
		return repr(self.parent.data[self.idx])

	def __setitem__(self, subIdx, item):
		index = (self.idx * self.parent.col) + subIdx
		self.parent.data[index] = item

	def __getitem__(self, subIdx):
		index = (self.idx * self.parent.col) + subIdx
		return self.parent.data[index]

class flatMatrix:
	def __init__(self, data):
		self.data = data
		self.col = 4

	def __setitem__(self, key, item):
		return SubItem(self, key, item) 

	def __getitem__(self, idx):
		return SubItem(self, idx)

A = flatMatrix([0,1,2,3,
		4,5,6,7,
		8,9,10,11,
		12,13,14,15])

print A[0][0]

A[0][0] = 50

print A[0][0]

I think its kind of cool. Not so sure I dig how complex it is to read though.
-RyanT

Leave a Reply