page86.html

来自「Data Structures And Algorithms With Obje」· HTML 代码 · 共 39 行

HTML
39
字号
<HTML><HEAD><TITLE>__getitem__ and __setitem__ Methods</TITLE></HEAD><BODY bgcolor="#FFFFFF"> <a href="../index.html" target="_top"><img src="../icons/usins.gif" alt="Logo" align=right></a><b>Data Structures and Algorithms with Object-Oriented Design Patterns in Python</b><br><A NAME="tex2html2200" HREF="page87.html"><IMG WIDTH=37 HEIGHT=24 ALIGN=BOTTOM ALT="next" SRC="../icons/next_motif.gif"></A> <A NAME="tex2html2198" HREF="page82.html"><IMG WIDTH=26 HEIGHT=24 ALIGN=BOTTOM ALT="up" SRC="../icons/up_motif.gif"></A> <A NAME="tex2html2192" HREF="page85.html"><IMG WIDTH=63 HEIGHT=24 ALIGN=BOTTOM ALT="previous" SRC="../icons/previous_motif.gif"></A>  <A NAME="tex2html2202" HREF="page611.html"><IMG WIDTH=43 HEIGHT=24 ALIGN=BOTTOM ALT="index" SRC="../icons/index_motif.gif"></A> <BR><HR><H2><A NAME="SECTION004140000000000000000"><tt>__getitem__</tt> and <tt>__setitem__</tt> Methods</A></H2><P>The elements of a Python list are accessed by enclosing theindex expression between brackets <tt>[</tt> and <tt>]</tt> like this:<PRE>a[2] = b[3]</PRE>In order to be able to use the same syntax to access the elementsof a <tt>Array</tt> object,we define the <tt>__getitem__</tt> and <tt>__setitem__</tt> methodsas shown in Program&nbsp;<A HREF="page86.html#progarrayc"><IMG  ALIGN=BOTTOM ALT="gif" SRC="../icons/cross_ref_motif.gif"></A><P><P><A NAME="2899">&#160;</A><A NAME="progarrayc">&#160;</A> <IMG WIDTH=575 HEIGHT=294 ALIGN=BOTTOM ALT="program2765" SRC="img587.gif"  ><BR><STRONG>Program:</STRONG> <tt>Array</tt> class <tt>__getitem__</tt> and <tt>__setitem__</tt> methods.<BR><P><P>Both <tt>__getitem__</tt> and <tt>__setitem__</tt>invoke the <tt>getOffset</tt> method to translate the given indexby subtracting from it the value of the <tt>_baseIndex</tt> instance attribute.In this way arbitrary subscript ranges are supported.Since the overhead of this subtraction is constant,the running times of the <tt>__getitem__</tt> and <tt>__setitem__</tt> methodsare <I>O</I>(1).<P><HR><A NAME="tex2html2200" HREF="page87.html"><IMG WIDTH=37 HEIGHT=24 ALIGN=BOTTOM ALT="next" SRC="../icons/next_motif.gif"></A> <A NAME="tex2html2198" HREF="page82.html"><IMG WIDTH=26 HEIGHT=24 ALIGN=BOTTOM ALT="up" SRC="../icons/up_motif.gif"></A> <A NAME="tex2html2192" HREF="page85.html"><IMG WIDTH=63 HEIGHT=24 ALIGN=BOTTOM ALT="previous" SRC="../icons/previous_motif.gif"></A>  <A NAME="tex2html2202" HREF="page611.html"><IMG WIDTH=43 HEIGHT=24 ALIGN=BOTTOM ALT="index" SRC="../icons/index_motif.gif"></A> <P><ADDRESS><img src="../icons/bruno.gif" alt="Bruno" align=right><a href="../copyright.html">Copyright &#169; 2003</a> by <a href="../signature.html">Bruno R. Preiss, P.Eng.</a>  All rights reserved.</ADDRESS></BODY></HTML>

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?