zoukankan      html  css  js  c++  java
  • python类与对象各个算数运算魔法方法总结

    1、python类与对象各个算术运算魔法方法总结:

    2、各个魔法方法应用举例:

    3、实例训练:

    (1)我们都知道在 Python 中,两个字符串相加会自动拼接字符串,但遗憾的是两个字符串相减却抛出异常。因此,现在我们要求定义一个 Nstr 类,支持字符串的相减操作:A – B,从 A 中去除所有 B 的子字符串。

    class Nstr(str):

        def __sub__(self,other):

            self=list(self)

            other=list(other)

            for i in other:

                c=len(self)

                while(c>0):

                    if i in self:

                        self.remove(i)

                    c=c-1

            x=""

            for j in range(len(self)):

                x=x+self[j]

            return x

    a = Nstr('I love iiiiii FishC.com!iiiiiiii')

    b = Nstr('i')

    print(a-b)

    (2)定义一个类 Nstr,当该类的实例对象间发生的加、减、乘、除运算时,将该对象的所有字符串的 ASCII 码之和进行计算:

    class Nstr(str):

        def __add__(self,other):

            y=0

            z=0

            for i in self:

                x=ord(i)

                y=y+x

            for j in other:

                q=ord(j)

                z=z+q

            return int(y)+int(z)

        def __sub__(self,other):

            y=0

            z=0

            for i in self:

                x=ord(i)

                y=y+x

            for j in other:

                q=ord(j)

                z=z+q

            return int(y)-int(z)

        def __mul__(self,other):

            y=0

            z=0

            for i in self:

                x=ord(i)

                y=y+x

            for j in other:

                q=ord(j)

                z=z+q

            return int(y)*int(z)

        def __truediv__(self,other):

            y=0

            z=0

            for i in self:

                x=ord(i)

                y=y+x

            for j in other:

                q=ord(j)

                z=z+q

            return int(y)/int(z)

        def __floordiv__(self,other):

            y=0

            z=0

            for i in self:

                x=ord(i)

                y=y+x

            for j in other:

                q=ord(j)

                z=z+q

            return int(y)//int(z)

  • 相关阅读:
    ALV_TREE(二:cl_gui_simple_tree…
    ALV_TREE(一:cl_gui_alv_tree_si…
    SQLPlus命令详细说明
    PL/SQL中,declare定义变量和variable定义变量的区别?
    Oracle 多表视图更新(待看完触发器后再来看)
    Oracle 函数 Translate 的用法
    Merge into
    savepoint(回退点)
    Oracle之分页查询
    对于package中全局变量的一点点初级理解
  • 原文地址:https://www.cnblogs.com/Yanjy-OnlyOne/p/10068828.html
Copyright © 2011-2022 走看看