Python自学成才之路 魔术方法之一元,二元运算符

时间:2022-07-23
本文章向大家介绍Python自学成才之路 魔术方法之一元,二元运算符,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

文章目录

一元运算符

一元运算符有+,-,~等,要想使这些一元运算符对对象起作用,需要在定义类的时候实现对应的魔术方法。

定义一个坐标类

class Coordinate(object):

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __pos__(self):
        return self

    def __neg__(self):
        return Coordinate(-self.x, -self.y)

    def __abs__(self):
        new_coordinate = Coordinate(abs(self.x), abs(self.y))
        return new_coordinate

    def __invert__(self):
        new_coordinate = Coordinate(360 - self.x, 360 - self.y)
        return new_coordinate

    def __str__(self):
        return "(%s, %s)" % (self.x, self.y)

_pos_, _neg_, _abs_, __invert__都是魔术方法,他们的作用分别如下。

__pos__函数

在对象前面使用+的时候会被调用,类中定义的是直接返回对象本身。

c1 = Coordinate(-100, -200)
print(c1)

print(+c1)
输出:
(-100, -200)
(-100, -200)

__neg__函数

在对象前面使用-的时候会后会被调用,这里返回坐标都是相反数的新对象。

c1 = Coordinate(-100, -200)
print(c1)
c2 = -c1
print(c2)
输出:
(-100, -200)
(100, 200)

__abs__函数

在给对象执行abs的时候会被调用,这里返回坐标绝对值的新对象

c1 = Coordinate(-100, -200)
print(abs(c1))
输出:
(100, 200)

__invert__函数

在对象前面使用~的时候会被调用,这里返回通过360减掉之后的新坐标对象。

c1 = Coordinate(-100, -200)
print(~c1)
输出:
(460, 560)

注意:这些魔术方法并不需要有返回值,比如上面的__neg__也可以修改对象本身,像下面这样。

def __neg__(self):
    self.x = -self.x
    self.y = -self.y

c1 = Coordinate(-100, -200)
print(c1)
-c1
print(c1)
输出:
(-100, -200)
(100, 200)

二元运算符

二元运算符是作用在两个元素上的,比如+,-,*,都是二元运算符。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : MagicBinaryOperator.py
# @Author: RicLee
# @Date  : 2020/8/10
# @Desc  :


class Coordinate(object):

    def __init__(self, x, y):
        self.x = x
        self.y = y

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

    def __sub__(self, other):
        x = self.x - other.x
        y = self.y - other.y
        return Coordinate(x, y)

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

    def __truediv__(self, other):
        x = self.x / other.x
        y = self.y / other.y
        return Coordinate(x, y)

    def __floordiv__(self, other):
        x = self.x // other.x
        y = self.y // other.y
        return Coordinate(x, y)

    def __mod__(self, other):
        x = self.x % other.x
        y = self.y % other.y
        return Coordinate(x, y)

    def __str__(self):
        return "(%s, %s)" % (self.x, self.y)


c1 = Coordinate(-100, -200)
c2 = Coordinate(200, 300)
c3 = c1 + c2
print(c3)
c4 = c1 - c2
print(c4)
c5 = c1 * c2
print(c5)
c6 = c1 / c2
print(c6)
c7 = c1 // c2
print(c7)
c8 = c1 % c2
print(c8)
输出:
(100, 100)
(-300, -500)
(-20000, -60000)
(-0.5, -0.6666666666666666)
(-1, -1)
(100, 100)

用法还是很简单的,我就不赘叙了,每个函数的作用如下: _add_(self, other):对象相加时被调用 _sub_:对象相减时被调用 _mul_:对象相乘时被调用 _truediv_:对象相除时被调用,Python3中两个整数相除得到的会是浮点数 _floordiv_:使用//时被调用,只保留商整数部分 _mod_:对象取模时会被调用