BrightXiong 发表于 2023-2-16 21:47:55

运算方法

# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time   : 2023/2/16 21:00
# @Author : xiongming
# @File   : yunsuanfangfa.py
# @Desc   : 运算方法

def S(str):
    def __add__(self, other):
      return len(self) + len(other)

s1 = S("FishC")
s2 = S("Python")
# s1 + s2 == s1.__add__(s2)
# s1 + "Python"   11
# "FishC" + s2    "FishCPython"

def S1(str):
    def __add__(self, other):
      return NotImplemented

def S2(str):
    def __radd__(self, other):
      return len(self) + len(other)

s1 = S1("Apple")
s2 = S2("Banana")
# s1 + s2   11

class S3(str):
    def __iadd__(self, other):
      return len(self) + len(other)

s3 = S3("Apple")
# s3 += s2
# s3   11
# type(s3) <class 'int'>
页: [1]
查看完整版本: 运算方法