[note]特殊方法

#!usr/bin/env python
#coding=utf-8

from math import hypot

class Vector(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, otherVec):
        return Vector(self.x+otherVec.x, self.y+otherVec.y)

    def __mul__(self, scalar):
        return Vector(self.x*scalar, self.y*scalar)

    def __sub__(self, otherVec):
        return Vector(self.x-otherVec.x, self.y-otherVec.y)

    def __repr__(self):
        return "Vector({},{})".format(self.x, self.y)

    def __abs__(self):
        return hypot(self.x, self.y)

    def __bool__(self):
        return bool(self.x or self.y)

a = Vector(3, 4)
print(a*3)
print(a*4)
print(abs(a))
print(a-Vector(4,1))
print(a+Vector(4,1))
print(bool(a))
print(bool(Vector(0,0)))

python类中类似__XX__ 的方法,叫特殊方法。上面的__add__, __mul__等等都是运算符的特殊方法。
注意__bool__返回值为bool(self.x or self.y),这个bool很有必要,否则返回值是self.x 或者 self.y。因为对于x or y来说,如果bool(x)为真返回x,如果bool(x)不为真,bool(y)为真返回y,都不为真,返回y。

Special method names (operators excluded)

类别方法名称
String/bytes representation__repr__ , __str__ , __format__ , __bytes__
Conversion to number__abs__ , __bool__ , __complex__ , __int__ , __float__ , __hash__ , __index__ ,
Emulating collections__len__ , __getitem__ , __setitem__ , __contains__ , __delitem__ ,
Iteration__iter__ , __reversed__ , __next__ ,
Emulating callable__call__
Context management__enter__ , __exit__ ,
Instance creation and destruction__init__ , __new__ , __del__ ,
Attribute management__getattr__ , __setattr__ , __delattr__ , __getattribute__ , __dir__ ,
Attribute descriptor__get__ , __set__ , __delete__
Class service__prepare__ , __instancecheck__ , __subclasscheck__

Special method names for operators

类别方法名称
Unary numeric operators__neg__ (-), __pos__ (+), __abs__ (abs())
Rich comparison operators__lt__ (<), __le__ (<=) , __eq__ (==), __gt__ (>) , __ge__ (>=), __ne__ (!=)
Arithmetic operators__add__ (+), __sub__ (-), __mul__ (*), __truediv__ (/), __floordiv__ (//), __mod__ (%), __divmod__ (divmod()),__pow__ (**,pow()), __round__ (round()),
Reversed arithmetic operators__radd__ , __rsub__ , __rmul__ , __rtruediv__ , __rfloordiv__ , __rmod__ , __rdivmod__ , __rpow__ ,
Augmented assignment arithmetic operators__iadd__ , __isub__ , __imul__ , __itruediv__ , __ifloordiv__ , __imod__ , __ipow__ ,
Bitwise operators__invert__ (~), __lshift__ (<<), __rshift__ (>>), __and__ (&), __or__ (|), __xor__ (^)
Reversed bitwise operators__rlshift__ , __rrshift__ , __rand__ , __ror__ , __rxor__
Augmented assignment bitwise operators__ilshift__ , __irshift__ , __iand__ , __ior__ , __ixor__ ,
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值