Python 属性可调用 [英] Python property callable

查看:80
本文介绍了Python 属性可调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法让一个属性和一个方法同名?我的意思是可以使用通常的方式同时调用的属性?像这样:

<预><代码>>>>b = 书()>>>b.页面123>>>b.pages()123>>>b.pages(包括_toc=False)123>>>b.pages(包括_toc=True)127

解决方案

不,你不能.

() 总是从其左侧的表达式调用对象.

这意味着,b.pages() 可以这样读:

_tmp = b.pages_tmp()

如您所见,方法属性.

可以(但不应该)做的是将整数包装在某个自定义类中并提供一个 __call__ 方法…但我建议不要使用这种黑魔法.

Is there any way to have a property and a method with the same name? I mean a property that can be used the usual way and to be callable at the same time? Like this:

>>> b = Book()
>>> b.pages
123
>>> b.pages()
123
>>> b.pages(including_toc=False)
123
>>> b.pages(including_toc=True)
127

解决方案

No, you can't.

() always calls an object from the expression on its left-hand side.

What this means is, that b.pages() can be read as follows:

_tmp = b.pages
_tmp()

As you can see, methods are attributes.

What you could (but shouldn't) do is wrap integers in some custom class and provide a __call__ method… but I would advise against such black magic.

这篇关于Python 属性可调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆