文章目录
- P132 魔术方法
- 1. 魔术方法的基本介绍
- 2. 常见的魔术方法
- 2.1 __str__
- 2.2 __eq__
- 2.3 其它的几个魔术方法
P132 魔术方法
1. 魔术方法的基本介绍
2. 常见的魔术方法
2.1 str
class Monster:def __init__(self, name, age, gender):self.name = nameself.age = ageself.gender = gender"""说明:1. 在默认情况下,调用的是父类Object的__str__2. 父类Object的__str__返回的就是类型+地址3. 可以根据需要重写__str__"""def __str__(self):return f"{self.name}, {self.age}, {self.gender}"m = Monster("青牛怪", 500, '男')print(m)
2.2 eq
- 基本介绍
- 应用实例
class Person:name = Noneage = Nonegender = Nonedef __init__(self, name, age, gender):self.name = nameself.age = age
p1 = Person("smith",20,"男")
p2 = Person("smith",20,"男")print(f"p1==p2: {p1 == p2}")
class Person:name = Noneage = Nonegender = Nonedef __init__(self, name, age, gender):self.name = nameself.age = ageself.gender =genderdef __eq__(self, other):if isinstance(other,Person):return self.name == other.name and \self.age == other.age and \self.gender == other.genderreturn Falseclass Dog:name = Noneage = Nonegender = Nonedef __init__(self, name, age, gender):self.name = nameself.age = ageself.gender = gender
p1 = Person("smith", 20, "男")
p2 = Person("smith", 20, "男")dog = Dog("smith", 20, "男")print(f"p1==p2: {p1 == p2}")
print(f"p1==p2: {dog == p2}")
2.3 其它的几个魔术方法
class Person:name = Noneage = Nonegender = Nonedef __init__(self, name, age, gender):self.name = nameself.age = ageself.gender = genderdef __eq__(self, other):if isinstance(other, Person):return self.name == other.name and \self.age == other.age and \self.gender == other.genderreturn Falsedef __lt__(self, other):if isinstance(other, Person):return self.age < other.agereturn "类型不一致,不能比较"def __le__(self, other):if isinstance(other, Person):return self.age <= other.agereturn "类型不一致,不一致"def __ne__(self, other):return not self.__eq__(other)class Dog:name = Noneage = Nonegender = Nonedef __init__(self, name, age, gender):self.name = nameself.age = ageself.gender = gender
p1 = Person("smith", 20, "男")
p2 = Person("smith", 20, "男")dog = Dog("smith", 20, "男")
print(f"p1 < p2 {p1 < p2}")
print(f"p1 <= p2 {p1 <= p2}")