Python魔法函数(和)

__abs__

魔法函数__abs__用于定义对象的绝对值操作。

创建类Victor,实现__abs__方法,定义对象的绝对值是x的绝对值加上y的绝对值

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

    def __repr__(self):
        return "Victor(%r,%r)" % (self.x, self.y)

    def __str__(self):
        return "Victor,x=%f,y=%f" % (self.x, self.y)

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

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

    def __abs__(self):
        return abs(self.x) + abs(self.y)

创建Victor对象进行测试,当对对象使用abs函数时,解释器会自动调用__abs__方法。

v1 = Victor(1,2)
print(abs(v1))

__bool__

Python魔法函数__bool__用于定义对象的布尔值。

在类Victor中实现__bool__方法,规定当x和y的和为0是返回False,否则返回True。

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

    def __repr__(self):
        return "Victor(%r,%r)" % (self.x, self.y)

    def __str__(self):
        return "Victor,x=%f,y=%f" % (self.x, self.y)

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

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

    def __abs__(self):
        return abs(self.x) + abs(self.y)

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

创建Victor对象,使用bool函数,Python解释器会自动调用对象的__bool__方法。

v1 = Victor(1,2)
print(bool(v1))

展开阅读全文

页面更新:2024-06-18

标签:函数   魔法   绝对值   定义   对象   操作   方法

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top