内置函数重写_运算符重载

内置函数重写

class Car:
    def __init__(self, brand="", price=0,max_speed = 0):
        self.brand = brand
        self.price = price
        self.max_speed = max_speed

    # 对人友好的 --> 随心所欲的规定字符串内容
    def __str__(self):
        return "品牌是%s,单价是%d"%(self.brand,self.price)

    # 对解释器友好 --> 根据python语法规定字符串内容
    def __repr__(self):
        return "Car('%s',%d,%d)"%(self.brand,self.price,self.max_speed)

# 应用:将对象显示出来
c01 = Car("宝马",1000000,260)
print(c01) # print(str(c01)) --> print(c01.__str__())
print(c01.__str__())
# 将括号中的字符串,作为python代码执行.
# re = eval("1 + 2")# 3
# repr(c01) -->  c01.__repr__()

# 应用:克隆(重新创建与之前对象数据相同的新对象,克隆对象与原对象互不影响)
c02 = eval(repr(c01))# eval("Car("宝马",1000000,260)")
c01.price = 50
print(c02.price)#1000000

 运算符重载

class Vector:
    """
        向量
    """

    def __init__(self, x=0):
        self.x = x

    def __str__(self):
        return "分量是:" + str(self.x)

    # 算数运算符 --> 返回新结果
    def __add__(self, other):
        """
             当前对象与其他数据相加时被自动调用
        :param other: 其他数据
        :return: 向量
        """
        # 如果other 是 向量
        if type(other) == Vector:
            return Vector(self.x + other.x)
        # 否则
        else:
            return Vector(self.x + other)

    def __rsub__(self, other):
        return Vector(other - self.x)

    # 复合运算符 --> 在原有对象基础上修改
    def __iadd__(self, other):
        self.x += other
        return self

    def __gt__(self, other):
        return self.x  > other.x

# 1. 算数运算符
v01 = Vector(10)
# 自定义向量 + 整数  -->  向量
print(v01 + 5)  # v01.__add__(5)
# 自定义向量 + 自定义向量  -->  向量
v02 = Vector(2)
print(v01 + v02)
原文地址:https://www.cnblogs.com/NeverYa/p/11224611.html