Python:如何将多个参数传递给属性 getter? [英] Python: How to pass more than one argument to the property getter?

查看:50
本文介绍了Python:如何将多个参数传递给属性 getter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下示例:

class A:
    @property
    def x(self): return 5

所以,当然调用 a = A();a.x 将返回 5

So, of course calling the a = A(); a.x will return 5

但是假设您希望能够修改属性 x.
这样,例如:

But imagine that you want to be able to modify the property x.
This way, for example:

class A:
    @property
    def x(self, neg = False): return 5 if not neg else -5

并用 a = A(); 调用它a.x(neg=True)

这将引发 TypeError: 'int' object is not callable,这是很正常的,因为我们的 x 被评估为 5.

That will raise a TypeError: 'int' object is not callable, that is quite normal, since our x is evaluated as 5.

所以,如果可能的话,我想知道如何将多个参数传递给属性 getter.

So, I would like to know how one can pass more then one argument to the property getter, if it is possible at all.

推荐答案

请注意,您不必使用 property 作为装饰器.您可以很高兴地以旧方式使用它,并在属性之外公开各个方法:

Note that you don't have to use property as a decorator. You can quite happily use it the old way and expose the individual methods in addition to the property:

class A:
    def get_x(self, neg=False):
        return -5 if neg else 5
    x = property(get_x)

>>> a = A()
>>> a.x
5
>>> a.get_x()
5
>>> a.get_x(True)
-5

这可能是也可能不是一个好主意,具体取决于您正在用它做什么(但如果我在我正在审查的任何代码中遇到这种模式,我希望在评论中看到一个很好的理由)

This may or may not be a good idea depending on exactly what you're doing with it (but I'd expect to see an excellent justification in a comment if I came across this pattern in any code I was reviewing)

这篇关于Python:如何将多个参数传递给属性 getter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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