python方法重载_Python 如何重载?

wangyongbo

2018-07-21 23:49:33 +08:00

这两天升级 django , 从 1.8 升级到 支持 python2.7 的最后一个版本 1.11.

发现

"Using user.is_authenticated() and user.is_anonymous() as a method "

"is deprecated. Remove the parentheses to use it as an attribute.",

之前的使用方法:user.is_authenticated()

现在的使用方法:user.is_authenticated

我看了一下 django 的实现方法

```

class User():

@property

def is_authenticated(self):

return CallableFalse

```

首先用 property 把它变成了一个属性,但是返回的不是一个 bool, 是一个有__call__ 的对象

CallableFalse = CallableBool(False)

```

class CallableBool:

"""

An boolean-like object that is also callable for backwards compatibility.

"""

do_not_call_in_templates = True

def __init__(self, value):

self.value = value

def __bool__(self):

return self.value

def __call__(self):

warnings.warn(

"Using user.is_authenticated() and user.is_anonymous() as a method "

"is deprecated. Remove the parentheses to use it as an attribute.",

RemovedInDjango20Warning, stacklevel=2

)

return self.value

def __nonzero__(self): # Python 2 compatibility

return self.value

def __repr__(self):

return 'CallableBool(%r)' % self.value

def __eq__(self, other):

return self.value == other

def __ne__(self, other):

return self.value != other

def __or__(self, other):

return bool(self.value or other)

def __hash__(self):

return hash(self.value)

```

你觉得这种实现方式 怎么样?

出了 这种需要兼容的代码, 再也没有见过 类似的代码了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值