0x01:比较运算符相关魔法方法

  1. class Student:
  2. def __init__(self, name, age):
  3. self.name = name
  4. self.age = age
  5. def __eq__(self, other):
  6. return self.name == other.name and self.age == other.age
  7. # def __ne__(self, other):
  8. def __lt__(self, other):
  9. return self.age < other.age
  10. # def __gt__(self, other):
  11. def __le__(self, other):
  12. return self.age <= other.age
  13. # def __ge__(self, other):
  14. s1 = Student('zhangsan', 18)
  15. s2 = Student('zhangsan', 18)
  16. s3 = Student('lisi', 20)
  17. print(s1 == s2)
  18. print(s1 != s2)
  19. print(s1 > s2)
  20. print(s1 >= s2)
  21. print(s1 <= s2)
  22. print(s1 <= s2)

0x02:算数运算符相关魔法方法

  1. class Student:
  2. def __init__(self, name, age):
  3. self.name = name
  4. self.age = age
  5. def __add__(self, other):
  6. return self.age + other
  7. def __sub__(self, other):
  8. return self.age - other
  9. def __mul__(self, other):
  10. return self.age * other
  11. def __truediv__(self, other):
  12. return self.age / other
  13. def __mod__(self, other):
  14. return self.age % other
  15. def __pow__(self, power, modulo=None):
  16. return self.age ** power
  17. s = Student('zhangsan', 18)
  18. print(s + 1) # 19
  19. print(s - 2) # 16
  20. print(s * 2) # 36
  21. print(s / 5) # 3.6
  22. print(s % 5) # 3
  23. print(s ** 2) # 324

0x03:类型转换相关魔法方法

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __int__(self):
        return self.age

    def __float__(self):
        return self.age * 1.0

    def __str__(self):
        return self.name

    def __bool__(self):
        return self.age > 18


s = Student('zhangsan', 18)
print(int(s))
print(float(s))
print(str(s))
print(bool(s))

if s:
    print('hello')