魔术方法 Python's Magic Methods

2020-05-07  本文已影响0人  RayRaymond

构建和初始化

实际使用

from os.path import join
class FileObject:
    '''对文件对象的包装,确保文件在关闭时得到删除'''
                                                     
    def __init__(self, filepath='~', filename='sample.txt'):
        # 按filepath,读写模式打开名为filename的文件
        self.file=open(join(filepath,filename), 'r+')
                                                         
    def __del__(self):
        self.file.close()
        del self.file

使操作符在自定义类内工作

使用 Python 魔术方法的优势之一就是它提供了一种简单的方式能让对象的行为像内建类型。我们可以使用魔术方法定义运算符的意义。

比较

P.S.

  1. 比较的时候,优先使用__gt__(),__lt__(), __eq__(),如果找不到则使用__cmp__()
  2. @total_ordering可以在重载__eq__和随意一个其他比较(__gt__等等)的情况下补全其他比较。可以节省大量时间

实例

比较两个字符串长度

class Word(str):
    '''单词类,比较定义是基于单词长度的'''
                                            
    def __new__(cls, word):
        # 注意,我们使用了__new__,这是因为str是一个不可变类型,
        # 所以我们必须更早地初始化它(在创建时)
        if ' ' in word:
            word = word[:word.index(' ')] # 截断至第一个空格处
            print(f'单词内含有空格,截断到{word}')
        return str.__new__(cls, word)
                                                
    def __gt__(self, other):
        return len(self) > len(other)
    def __lt__(self, other):
        return len(self) < len(other)
    def __ge__(self, other):
        return len(self) >= len(other)
    def __le__(self, other):
        return len(self) <= len(other)
    def __eq__(self, other):
        return len(self) == len(other)
    
print('abc'<'cbe')
print(Word('ab c') == Word('cb'))

数字操作符

类行为的描述

属性访问控制

调用

Reference

[1] A Guide to Python's Magic Methods - Rafe Kettler

上一篇 下一篇

猜你喜欢

热点阅读