page596.html

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

HTML
37
字号
<HTML><HEAD><TITLE>Operator Overloading</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="tex2html8001" HREF="page597.html"><IMG WIDTH=37 HEIGHT=24 ALIGN=BOTTOM ALT="next" SRC="../icons/next_motif.gif"></A> <A NAME="tex2html7999" HREF="page591.html"><IMG WIDTH=26 HEIGHT=24 ALIGN=BOTTOM ALT="up" SRC="../icons/up_motif.gif"></A> <A NAME="tex2html7993" HREF="page595.html"><IMG WIDTH=63 HEIGHT=24 ALIGN=BOTTOM ALT="previous" SRC="../icons/previous_motif.gif"></A>  <A NAME="tex2html8003" HREF="page611.html"><IMG WIDTH=43 HEIGHT=24 ALIGN=BOTTOM ALT="index" SRC="../icons/index_motif.gif"></A> <BR><HR><H2><A NAME="SECTION0017450000000000000000">Operator Overloading</A></H2><P>Program&nbsp;<A HREF="page596.html#progcomplexd"><IMG  ALIGN=BOTTOM ALT="gif" SRC="../icons/cross_ref_motif.gif"></A> illustrates operator overloading in Python.<em>Operator overloading</em><A NAME=57084>&#160;</A><A NAME=57085>&#160;</A>allows the programmer to use the built-in operators for user-defined types.<P><P><A NAME="57511">&#160;</A><A NAME="progcomplexd">&#160;</A> <IMG WIDTH=575 HEIGHT=256 ALIGN=BOTTOM ALT="program57086" SRC="img2488.gif"  ><BR><STRONG>Program:</STRONG> <tt>Complex</tt> class <tt>__add__</tt>, <tt>__sub__</tt> and <tt>__mul__</tt>  methods.<BR><P><P>To overload the built-in <tt>+</tt>, <tt>-</tt> and <tt>*</tt> operators so thatthey may be used with <tt>Complex</tt> operands,we define the methods called<tt>__add__</tt>, <tt>__sub__</tt> and <tt>__mul__</tt> (respectively).Given <tt>Complex</tt> variables <tt>c</tt>, <tt>d</tt> and <tt>e</tt>,the expression<PRE>c + d * e</PRE>is equivalent to<PRE>Complex.__add__(c, Complex.__mul__(d, e))</PRE><P><HR><A NAME="tex2html8001" HREF="page597.html"><IMG WIDTH=37 HEIGHT=24 ALIGN=BOTTOM ALT="next" SRC="../icons/next_motif.gif"></A> <A NAME="tex2html7999" HREF="page591.html"><IMG WIDTH=26 HEIGHT=24 ALIGN=BOTTOM ALT="up" SRC="../icons/up_motif.gif"></A> <A NAME="tex2html7993" HREF="page595.html"><IMG WIDTH=63 HEIGHT=24 ALIGN=BOTTOM ALT="previous" SRC="../icons/previous_motif.gif"></A>  <A NAME="tex2html8003" 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 + -
显示快捷键?