SICP-Notes-Lecture 14 Special Methods

Lecture 14 Special Methods

These are my notes for SICP(Structure and Interpretation of Computer Programs). Hope they’ll be of some help to you.

Outline

  • Polymorphism
  • Polymorphism Functions(__str__, __repr__)
  • Operator Overloading (+ and __add__)
  • More Special Methods

Polymorphism

  • Ad Hoc Polymorphism

    • e.g. Overloading: foo(int) { xxx } foo(string) {xxx xxx xx}
  • Parametric Polymorphism

    • e.g. Generic functions:

      Template <typename T>
      T foo(T x, T y){
          return (x > y) ? x : y;
      }
      foo<int>(3, 7);
      foo<char>('h', 'k');
      
  • Inclusion Polymorphism

    • Subtypes and inheritance

Next, we introduce two instances of ad hoc polymorphism to help illustrate some important special methods in Python:

polymorphic function (__str__, __repr__)

operator overloading (__add__)

String Representations

  • An object value should behave like the kind of data it is meant to represent

  • For instance, by producing a string representation of itself

  • String are important: they represent language and programs

  • In Python, all objects produce two string representations:

    • The str is legible to humans
    • The repr is legible to the python interpreter

    The str and repr strings are often the same, but not always

The repr string for an object
  • repr:

    • string representation of Python object. For most object types, eval will convert it back to that object, eval(repr(obj)) == obj

      >>> 2e3
      2000.0
      >>> repr(2e3)
      '2000.0'
      >>> eval(repr(2e3))
      2000.0
      
    • The result of calling repr on a value is what Python outputs in an interactive session

      >>> min
      <built-in function min>
      
      >>> repr(min)
      <built-in function min>
      
The str string for an object
  • Human interpretable string are useful as well:

    >>> from fractions import Fraction
    >>> half = Fraction(1, 2)
    >>> repr(half)
    'Fraction(1, 2)'
    >>> str(half)
    '1/2'
    
  • The result of calling str on the value of an expression is what Python prints using the print function:

    >>> print(half)
    1/2
    
>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2020, 9, 14, 10, 36, 46, 832676)
>>> repr(now)
'datetime.datetime(2020, 9, 14, 10, 36, 46, 832676)'
>>> str(now)
'2020-09-14 10:36:46.823676'

repr is to be unambiguous

str is to be readable

Polymorphic Functions

  • Polimorphic function:
    • A function that applies to many (ploy) different forms (morph) of data

Polymorphic functions behave differently depending on the types of the arguments come in, while parametric function execute the same code for arguments of any admissible types.

  • str and repr are both polimophic:

    • They apply to any object and do not have much logic, and thay defer to the object (comes in) to decide what to do

      • repe invokes a zero-argument method __repr__ on its argument

        >>> half.__repr__()
        'Function(1, 2)'
        
      • str invokes a zero-argument method __str__ on its argument

        >>> half.__str__()
        '1/2'
        
Implementing repr and str
  • The behavior of repr is slightly more complicated than invoking __repr__ on its argument:
    • An instance attribute called __repr__ is ignored! Only class attributes are found
  • The behavior of str is also complicated:
    • An instance attribute called __str__ is ignored
    • If no __str__ attribute is found, uses repr string

Operator Overloading

Operator overloading is to give the operator extended meaning beyond its predefined operational meaning.

e.g. adding instances of user-definded classes invokes __add__ method

>>> Ratio(1, 3) + Ratio(1, 6)
Ratio(1, 2)
>>> Ratio(1, 3).__add__(Ratio(1, 6))
Ratio(1, 2)
  • Operator ‘+’ is overloaded by __add__ method when ‘+’ is used to add user-defined objects
  • A + B, different behaviors of this adding expression may exhibit, depending on the types of the operands (A or B). Thus we say operator overloading is a kind of polymorphism.

Summary

Certain names are special because they have built-in behaviors

These names always start and end with two underscores

__init__Method invoked automatically when an object is constructed
__repr/str__Method invoked to display an object as a Python expression
__add/radd__Method invoked to add one object to another
__float__Method invoked to convert an object to a float(real number)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值