python面向对象编程__str__, __die__, __add__等

There are something i copied from :

http://www.greenteapress.com/thinkpython/thinkCSpy/html/chap14.html

这本书叫thinkpython


These would be very helpful :D

14.7 Points revisited

Let's rewrite the Point class fromSection 12.1 in a more object-oriented style:

class Point:
  def __init__(self, x=0, y=0):
    self.x = x
    self.y = y

  def __str__(self):
    return '(' + str(self.x) + ', ' + str(self.y) + ')'

The initialization methodtakes x and y values as optional parameters;the default for either parameter is 0.

The next method, __str__, returns a string representationof a Point object.If a class provides a method named __str__, itoverrides the default behavior of the Python built-in str function.

>>> p = Point(3, 4)
>>> str(p)
'(3, 4)'

Printing a Point object implicitly invokes __str__ onthe object, so defining __str__ also changes the behavior ofprint:

>>> p = Point(3, 4)
>>> print p
(3, 4)

When we write a new class, we almost always start by writing __init__, which makes it easier to instantiate objects, and __str__, which is almost always useful for debugging.  

下面还有!

很精彩的介绍


14.8 Operator overloading

Some languages make it possible to change the definition of thebuilt-in operators when they are applied to user-defined types. Thisfeature is called operator overloading. It is especially useful whendefining new mathematical types.

For example, to override the addition operator +, weprovide a method named __add__:

class Point:
  # previously defined methods here...

  def __add__(self, other):
    return Point(self.x + other.x, self.y + other.y)

As usual, the first parameter is the object on which the method isinvoked. The second parameter is conveniently named otherto distinguish it from self. To add two Points, we createand return a new Point that contains the sum of thex coordinates and the sum of the y coordinates.

Now, when we apply the + operator to Point objects, Pythoninvokes __add__:

>>>   p1 = Point(3, 4)
>>>   p2 = Point(5, 7)
>>>   p3 = p1 + p2
>>>   print p3
(8, 11)

The expression p1 + p2 is equivalent top1.__add__(p2), but obviously more elegant.

As an exercise, add a method __sub__(self, other) thatoverloads the subtraction operator, and try it out.

There are several ways to override the behavior of themultiplication operator: by defining a method named__mul__, or __rmul__, or both.

If the left operand of * is a Point, Python invokes__mul__, which assumes that the other operand is alsoa Point. It computes the dot product of the twopoints, defined according to the rules of linear algebra:

def __mul__(self, other):
  return self.x * other.x + self.y * other.y

If the left operand of * is a primitive type and the rightoperand is a Point, Python invokes __rmul__, whichperforms scalar multiplication:

def __rmul__(self, other):
  return Point(other * self.x,  other * self.y)

The result is a new Point whose coordinates are a multipleof the original coordinates. If other is a type that cannotbe multiplied by a floating-point number, then__rmul__ will yield an error.

This example demonstrates both kinds of multiplication:

>>> p1 = Point(3, 4)
>>> p2 = Point(5, 7)
>>> print p1 * p2
43
>>> print 2 * p2
(10, 14)

What happens if we try to evaluate p2 * 2? Sincethe first operand is a Point, Python invokes__mul__ with 2 as the second argument.Inside __mul__, the program tries to access the xcoordinate of other, which fails becausean integer has no attributes:

>>> print p2 * 2
AttributeError: 'int' object has no attribute 'x'

Unfortunately, the error message is a bit opaque. This exampledemonstrates some of the difficulties of object-oriented programming.Sometimes it is hard enough just to figure out what code is running.

For a more complete example of operator overloading, seeAppendix B.  



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值