Indexer (programming): Difference between revisions

Content deleted Content added
Dmt137 (talk | contribs)
added c++ example
Dmt137 (talk | contribs)
Implementation: added Python example
Line 83:
Jane is the member number 1 of the doeFamily
 
=== Python ===
In Python one implements indexing by overloading the {{python|__getitem__}} and {{python|__setitem__}} methods like in the following example.
==== Example ====
<syntaxhighlight lang="python">
import array
class vector (object) :
def __init__ (self,n) :
self.size=n
self.data=array.array('d',[0.0]*n)
def __getitem__ (self,i) : return self.data[i]
def __setitem__ (self,i,value) : self.data[i]=value
 
v=vector(3)
for i in range(v.size) : v[i]=i+1
for i in range(v.size) : print(v[i])
</syntaxhighlight>
 
== See also ==