python descriptor

In a nutshell, a descriptor is a way to customize what happens when you reference an attribute on a model. Normally, Python just gets and sets values on attributes without any special processing. It’s just basic storage. Sometimes, however, you might want to do more. You might need to validate the value that’s being assigned to a value. You may want to retrieve a value and cache it for later use, so that future references don’t have all the overhead.

__get__(self, instance, owner):当value = obj.attr)时被调用
__set__(self, instance, value):当obj.attr = 'value'时被调用
__delete__(self, instance):当从object中删除attribute时被调用

import random

class Die(object):
    def __init__(self, sides=6):
        self.sides = sides

    def __get__(self, instance, owner):
        return int(random.random() * self.sides) + 1

class Game(object):
    d6 = Die()
    d10 = Die(sides=10)
    d20 = Die(sides=20)

>>> Game.d6
5
>>> Game.d10
8
>>> Game.d20
19
>>> Game.d20
3
>>> game = Game()
>>> game.d20
12

参考
http://martyalchin.com/2007/nov/23/python-descriptors-part-1-of-2/
http://martyalchin.com/2007/nov/24/python-descriptors-part-2-of-2/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值