头歌实训 第7章-类-课后练习II-运算符重载

第1关 原始部落结绳算术类#**********Begin**********#

class Rope:  

    def __init__(self, knots):  # 初始化方法,knots表示绳子的结数

        self.knots = knots  # 将传入的结数赋值给对象的knots属性

 

    def __add__(self, other):  # 定义加法运算符的重载方法

        if isinstance(other, Rope):  # 如果另一个操作数是Rope类型的对象

            return Rope(self.knots + other.knots + 1)  # 返回一个新的Rope对象,其结数为两个操作数的结数之和加1

        elif isinstance(other, int):  # 如果另一个操作数是整数

            return Rope(self.knots + other + 1)  # 返回一个新的Rope对象,其结数为当前对象的结数与整数之和加1

 

 

    def __radd__(self, other):  # 定义反向加法运算符的重载方法,用于处理如 5 + rope 这样的操作

        return self.__add__(other)  # 调用__add__方法完成加法操作

 

    def __call__(self):  # 定义调用运算符的重载方法,用于将对象当作函数调用

        return self.knots  # 返回对象的knots属性

 

    def __str__(self):  # 定义字符串转换运算符的重载方法,用于将对象转换为字符串

        return str(self.knots)  # 返回knots属性的字符串表示

 


 

第2关 多参数数学函数类

from math import *

 

#**********Begin**********#

 

class G:

 

    def __init__(self, a, b):

        

        self.a = a

        self.b = b

 

 

    def value(self, x):

        return self.a * x**2 + sin(self.b * x)

 

    # 定义 __call__ 方法,使得类的实例可以像函数一样被调用

    def __call__(self, x):

 

        return self.value(x)

 

    # 定义 __str__ 方法,用于返回类的实例的字符串表示形式

    def __str__(self):

        # 返回格式化后的字符串,表示类的实例所代表的表达式

        return '{:.3f}*(x**2)+sin({:.3f}*x)'.format(self.a, self.b)

#***********End***********#

 

 

for a in [1.0, 2.0]:

   for b in [0.4, 0.5]:

       for x in [1.57, 3.14]:

           g = G(a, b)

           print('%.3f' % (g.value(x)))

           print('%.3f' % (g(x)))

           print(g)

 

 

 

 

 

 

#***********End***********#

 

for n in [1, 2]:

   for m in [1, 5]:

        rope1 = Rope(n)

        rope2 = Rope(m)

        rope3 = rope1 + rope2

        rope4 = rope1 + m

        rope5 = n + rope2

        print(rope1)

        print(rope2())

        print(rope3)

        print(rope4())

        print(rope5)

 

 


第3关 银行账户类#**********Begin**********#

 

class Account:

    def __init__(self, name, account_number, initial_amount):

        self.name = name

        self.no = account_number

        self.balance = initial_amount

    

# 定义 __iadd__ 方法,用于实现 += 运算符的重载

    def __iadd__(self, amount):

    # 将实例的 balance 属性与传入的 amount 相加

        self.balance += amount

 

        return self  

 

# 定义 __isub__ 方法,用于实现 -= 运算符的重载

    def __isub__(self, amount):

    # 将实例的 balance 属性减去传入的 amount

        self.balance -= amount

 

        return self

    def __str__(self):

        return 'name: %s, no: %s, balance: %s' % (self.name, self.no, self.balance)

 

 

 

 

 

 

#***********End***********#

 

for name in ['ZhangSan', 'LiSi']:

    for account_number in ['19371554951', '19371564762']:

        for initial_amount in [10000, 20000]:

            a = Account(name, account_number, initial_amount)

            a_id1 = id(a)

            a += 200

            a_id2 = id(a)

            if(a_id1 == a_id2):

                print(a)

            else:

                print('Error: Object ID has been changed.')

            a -= 50

            a_id3 = id(a)

            if(a_id1 == a_id3):

                print(a)

            else:

                print('Error: Object ID has been changed.')

 

 

 


第4关 支持列表/元组的二维向量类from math import *

 

class Vec2D:

    def __init__(self, x, y):

        self.x = x

        self.y = y

        self.epsilon = 1.0e-6

 

    def __abs__(self):

        return math.sqrt(self.x ** 2 + self.y ** 2)

 

    def __str__(self):

        return '(%.7f, %.7f)' % (self.x, self.y)

    

    #**********Begin**********#

    @staticmethod

    def convert2Vec2D(other):

        if isinstance(other, (list, tuple)):

            return Vec2D(other[0], other[1])

        return other

 

    def __add__(self, other):

        other = Vec2D.convert2Vec2D(other)

        return Vec2D(self.x + other.x, self.y + other.y)

 

    def __radd__(self, other):

        return self.__add__(other)

 

    def __sub__(self, other):

        other = Vec2D.convert2Vec2D(other)

        return Vec2D(self.x - other.x, self.y - other.y)

 

    def __rsub__(self, other):

        other = Vec2D.convert2Vec2D(other)

        return other.__sub__(self)

 

    def __mul__(self, other):

        other = Vec2D.convert2Vec2D(other)

        return self.x * other.x + self.y * other.y

 

    def __rmul__(self, other):

        return self.__mul__(other)

 

    def __eq__(self, other):

        other = Vec2D.convert2Vec2D(other)

        return abs(self.x - other.x) < self.epsilon and abs(self.y - other.y) < self.epsilon

 

    def __abs__(self):

        return math.sqrt(self.x ** 2 + self.y ** 2)

 

    def __str__(self):

        return '(%.7f, %.7f)' % (self.x, self.y)

 

 

 

 

 

 

 

 

    #***********End***********#

 

 

for xy1 in [(2.8, 3.9), [2.8, 3.9]]:

    for xy2 in [[7.2, 6.1], (7.2, 6.1)]:

        v1 = Vec2D.convert2Vec2D(xy1)

        v2 = Vec2D.convert2Vec2D(xy2)

        vadd1 = v1 + v2

        vadd2 = v1 + xy2

        vadd3 = xy2 + v1

        vsub1 = v1 - v2

        vsub2 = v1 - xy2

        vsub3 = xy2 - v1

        vmul1 = v1 * xy2

        vmul2 = xy2 * v1

        print(vadd1)

        print(vadd2)

        print(vadd3)

        print(vsub1)

        print(vsub2)

        print(vsub3)

        print(vmul1)

        print(vmul2)   

        if (vadd1 == Vec2D(10.0000005, 10.0000005)):

            print('Equal')

        else:

            print('Error: __eq__ and __ne__ are not correctly implemented')

 

 

 

 

  • 23
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值