美文网首页
Python 魔术方法(Magic Methods)- 2

Python 魔术方法(Magic Methods)- 2

作者: SingleDiego | 来源:发表于2020-03-27 15:58 被阅读0次

参考资料:https://rszalski.github.io/magicmethods/#access




  • __getattr__(self, name)
    该方法可以定义用户访问一个实例不存在的属性时的行为,一般用来抛出错误。
from builtins import AttributeError 

class People:

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

    def __getattr__(self, name):
        raise AttributeError('该属性不存在')

tom = People(18)
print(tom.name)

>>> AttributeError: 该属性不存在
  • __setattr__(self, name, value)
    该方法可以控制设置某个实例的属性时(就是:实例名.属性名 = 值 这种结构)的行为,它操控的是实例的 __dict__ 属性。
class People:

    def __init__(self, age):
        self.age = age
    
    def __setattr__(self, key, value):
        if key == 'age' and value > 0 and value <= 120:
            self.__dict__[key] = value
        if key != 'age':
            self.__dict__[key] = value

tom = People(18)
tom.name = 'tom'
print(tom.__dict__)

>>> {'age': 18, 'name': 'tom'}

可见,实例的属性是保存在其 __dict__ 里面的。我们可以在 __setattr__ 设置值的检验。

tom = People(18)
tom.age = -20
print(tom.__dict__)

>>> {'age': 18}
  • __delattr__(self, name)
    该方法定义了 del 实例名.属性名 的行为,一般用来删除某属性。
class People:

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

    def __delattr__(self, name):
        if name == 'name':
            return 'name 字段不可删除'
        else:
            del self.__dict__[name]

tom = People('tom')
tom.age = 18
del tom.name
del tom.age
print(tom.__dict__)

>>> {'name': 'tom'}
  • __getattribute__(self, name)
    不建议使用

  • __len__(self)
    该方法定义了 len() 函数的行为,一般用来返回容器的长度。

class People:

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

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

tom = People('tom')
print(len(tom))

>>> 3
  • __getitem__(self, key)
    该方法定义 实例名[属性名] 这种访问的行为。
class People:

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

    def __getitem__(self, key):
        if key == 'name':
            return self.__dict__.get(key)
        else:
            return '该属性不存在'

tom = People('tom')
print(tom['name'])
print(tom['age'])

>>> tom
>>> 该属性不存在
  • __delitem__(self, key)
    该方法定义 del 实例名[属性名] 的行为,一般用于删除属性。
class People:

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

    def __delitem__(self, name):
        if name == 'name':
            return 'name 字段不可删除'
        else:
            del self.__dict__[name]

tom = People('tom')
tom.age = 18
del tom['name']
del tom['age']
print(tom.__dict__)

>>> {'name': 'tom'}
  • __iter__(self)
    该方法控制 iter() 函数的行为,用于返回一个可迭代对象。
class People:

    def __init__(self, name):
        self.name = name
        self.address = ['hangzhou', 'zhejiang', 'china']

    def __iter__(self):
        return iter(self.address)

tom = People('tom')
for i in iter(tom):
    print(i)

>>> hangzhou
    zhejiang
    china
  • __reversed__(self)
    该方法控制 reversed() 函数的行为,用于返回一个一个反向的可迭代对象。
class People:

    def __init__(self, name):
        self.name = name
        self.address = ['hangzhou', 'zhejiang', 'china']

    def __reversed__(self):
        return reversed(self.address)

tom = People('tom')
for i in reversed(tom):
    print(i)

>>> china
    zhejiang
    hangzhou
  • __contains__(self, item)
    该方法定义了 innot in 操作符的逻辑。
class People:

    def __init__(self, name):
        self.name = name
        self.age = 18
        self.address = ['hangzhou', 'zhejiang', 'china']

    def __contains__(self, item):
        if item in self.address:
            return True
        else:
            return False

tom = People('tom')
print('hangzhou' in tom)
print('beijing' not in tom)
print('changdu' in tom)

>>> True
    True
    False

相关文章

  • Python 魔术方法(Magic Methods)- 2

    参考资料:https://rszalski.github.io/magicmethods/#access __ge...

  • Python 魔术方法(Magic Methods)

    参考资料: https://pycoders-weekly-chinese.readthedocs.io/en/l...

  • 魔术方法 Python's Magic Methods

    构建和初始化 __new__(cls,[...)一个对象的实例化时 __new__ 是第一个被调用的方法。在类中传...

  • PHP魔术方法

    魔术方法(Magic methods) PHP中把以两个下划线__开头的方法称为魔术方法,这些方法在PHP中充当了...

  • Python类-magic methods魔术方法, since

    (2022.04.19-20 Tues-Wed)Python中的魔术方法,是可以定义在类中的特殊方法,可在特定的情...

  • php魔术方法

    PHP 中被称为魔术方法(Magic methods)。在命名自己的类方法时不能使用这些方法名,除非是想使用其魔术...

  • PHP 魔术方法

    前言PHP中把以两个下划线__开头的方法称为魔术方法(Magic methods),这些方法在PHP中充当了举足轻...

  • PHP魔术方法

    PHP中把以两个下划线__开头的方法称为魔术方法(Magic methods),这些方法在PHP中充当了举足轻重的...

  • Dunder methods & operator overlo

    link:https://www.python-course.eu/python3_magic_methods.p...

  • 流畅的Python

    第一章 Python数据模型魔术方法(magic method)或者说双下方法(dunder method)表示特...

网友评论

      本文标题:Python 魔术方法(Magic Methods)- 2

      本文链接:https://www.haomeiwen.com/subject/cbeluhtx.html