请解释Python中的`__int__`、`__float__`和`__str__`魔术方法在类型转换中的作用,并给出自定义类的示例。

在Python中,__int__、__float__和__str__是魔术方法(也称为特殊方法或双下方法),它们在类型转换中扮演着重要角色。这些方法允许开发者自定义类的实例在调用int()、float()和str()时的行为。以下是它们的详细说明和示例:

__int__ 方法

__int__方法用于定义对象如何被转换为整数。当调用int(obj)时,Python会自动调用对象的__int__方法。

示例

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __int__(self):
        return self.x + self.y

p = Point(3, 4)
print(int(p))  # 输出: 7

__float__ 方法

__float__方法用于定义对象如何被转换为浮点数。当调用float(obj)时,Python会自动调用对象的__float__方法。

示例

class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    def __float__(self):
        return float(self.celsius)

temp = Temperature(25.5)
print(float(temp))  # 输出: 25.5

__str__ 方法

__str__方法用于定义对象如何被转换为字符串。当调用str(obj)或使用print(obj)时,Python会自动调用对象的__str__方法。

示例

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

    def __str__(self):
        return f"{self.name} is {self.age} years old."

person = Person("Alice", 30)
print(str(person))  # 输出: Alice is 30 years old.

综合示例

下面是一个自定义类的综合示例,展示了__int__、__float__和__str__方法的结合使用:

class Measurement:
    def __init__(self, value, unit):
        self.value = value
        self.unit = unit

    def __int__(self):
        return int(self.value)

    def __float__(self):
        return float(self.value)

    def __str__(self):
        return f"{self.value} {self.unit}"

# 使用示例
meas = Measurement(10.5, "kg")
print(int(meas))    # 输出: 10
print(float(meas))  # 输出: 10.5
print(str(meas))    # 输出: 10.5 kg

注意事项

  1. 这些魔术方法的返回值必须符合对应的类型要求。例如,__int__必须返回整数,否则会抛出TypeError。
  2. __str__是对象的“用户友好”表示,而__repr__是“开发者友好”表示,两者不应混淆。
  3. 如果没有定义这些方法,直接调用int()或float()可能会引发错误,或者调用str()时返回默认的类表示(如<__main__.Point object at 0x...>)。

通过这些方法,开发者可以更灵活地控制自定义类的类型转换行为,使得类的实例能够无缝地与Python内置函数和操作符协同工作。