Python 魔法方法

1、和比较相关的魔法方法

方法用途
__eq__(self, other)self == other
__ne__(self, other)self != other
__lt__(self, other)self < other
__gt__(self, other)self > other
__le__(self, other)self <= other
__ge__(self, other)self >= other

示例代码:

class Person(object):

    def __init__(self, name, age):
        self.__name = name
        self.__age = age

    @property
    def name(self):
        return self.__name

    @name.setter
    def name(self, name):
        self.__name = name

    @property
    def age(self):
        return self.__age

    @age.setter
    def age(self, age):
        self.__age = age

    def __eq__(self, other):
        return self.__age == other.__age

    def __ne__(self, other):
        return self.__age != other.__age

    def __lt__(self, other):
        return self.__age < other.__age

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

    def __le__(self, other):
        return self.__age <= other.__age

    def __ge__(self, other):
        return self.__age >= other.__age


p1 = Person('zhangsan',20)
p2 = Person('lisi',20)
p3 = Person('wangwu',18)
p4 = Person('zhaoliu',25)

print(p1==p2)
print(p1==p3)
print(p1!=p2)
print(p1!=p4)
print(p1<p2)
print(p1<p4)
print(p1>p3)
print(p1>=p2)
print(p1<=p4)

2、和数学相关的魔法方法

方法用途
__add__(self, other)self + other
__sub__(self, other)self - other
__mul__(self, other)self * other
__floordiv__(self, other)self // other
__truediv__(self, other)self / other
__mod__(self, other)self % other
__pow__(self, other)self ** other

示例代码:

class Point(object):

    def __init__(self, x, y):
        self.__x = x
        self.__y = y

    @property
    def x(self):
        return self.__x

    @x.setter
    def x(self, x):
        self.__x = x

    @property
    def y(self):
        return self.__y

    @y.setter
    def y(self, y):
        self.__y = y

    def __add__(self, other):
        return Point(self.__x + other.__x, self.__y + other.__y)

    def __sub__(self, other):
        return Point(self.__x - other.__x, self.__y - other.__y)

    def __str__(self):
        return '('+str(self.__x)+','+str(self.__y)+')'

p1 = Point(4,5)
p2 = Point(1,2)

p3 = p1+p2
p4 = p1-p2

print(p1)
print(p2)
print('p1+p2:',p3)
print('p1-p2:',p4)

3、其他种类的魔术方法

方法用途
__str__(self)str(self)
__repr__(self)repr(self)
__len__(self)len(self)

示例代码:

class Word(object):

    def __init__(self, text):
        self.text = text

    def __len__(self):
        return len(self.text)

    def __str__(self):
        return self.text

    __repr__ = __str__

w = Word('hello world')
print(len(w))
print(w)
### Python 魔法方法的定义与使用 #### 什么是魔法方法? 在 Python 中,魔法方法是指那些前后带有双下划线的方法(即 `__method_name__`)。这些特殊命名的方法允许开发者自定义类的行为,并提供了一种机制来实现对象之间的操作符重载和其他内置功能。通过实现特定的魔法方法,可以改变 Python 默认行为以满足需求。 #### 常见的魔法方法及其作用 以下是几个常见的魔法方法及其具体用途: 1. **比较运算符重载** 可以通过实现一系列魔法方法来自定义对象间的比较逻辑。例如: - `__eq__(self, other)` 定义等于 (`==`) 的行为。 - `__ne__(self, other)` 定义不等于 (`!=`) 的行为。 - `__lt__(self, other)` 定义小于 (`<`) 的行为。 - `__le__(self, other)` 定义小于等于 (`<=`) 的行为。 - `__gt__(self, other)` 定义大于 (`>`) 的行为。 - `__ge__(self, other)` 定义大于等于 (`>=`) 的行为[^1]。 2. **属性访问控制** 使用 `__getattribute__` 方法可以深度控制对象属性的访问方式。此方法会在每次尝试获取对象属性时触发,相较于 `__getattr__` 更加灵活和强大[^3]。 3. **使对象可调用** 实现 `__call__` 方法可以让一个类的实例像函数一样被调用。这使得对象能够模拟函数的行为,从而增强代码的灵活性[^4]。 #### 示例代码展示 下面是一个综合示例,展示了如何利用上述几种魔法方法的功能: ```python class MyClass: def __init__(self, value): self.value = value # 自定义相等判断 def __eq__(self, other): if isinstance(other, MyClass): return self.value == other.value return False # 控制属性访问 def __getattribute__(self, name): attr = super().__getattribute__(name) if name == 'value': print(f"Accessing attribute '{name}' with value {attr}") return attr # 让对象支持调用 def __call__(self, *args): return sum(args) # 测试 obj1 = MyClass(10) obj2 = MyClass(10) print(obj1 == obj2) # 输出 True print(obj1.value) # 输出 Accessing attribute 'value' with value 10 并返回 10 print(obj1(1, 2, 3)) # 输出 6 ``` #### 协同程序的支持 除了以上提到的内容外,某些魔法方法还参与实现了更高级别的特性,比如协同程序(coroutine)。通过定义诸如 `__await__`, `__aiter__`, 和 `__anext__` 这样的方法,可以使对象具备异步迭代的能力[^5]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值