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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM