在方法内使用Python property() [英] Using Python property() inside a method

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

问题描述

假设您了解Python内置属性: http://docs.python.org /library/functions.html#property

Assuming you know about Python builtin property: http://docs.python.org/library/functions.html#property

我想以这种方式重新设置对象属性,但是,我需要在一个方法中能够传递一些参数,目前,property()的所有网络示例都在方法之外定义属性,并尝试显而易见的方法。

I want to re-set a object property in this way but, I need to do it inside a method to be able to pass to it some arguments, currently all the web examples of property() are defining the property outside the methods, and trying the obvious...

def alpha(self, beta):
  self.x = property(beta)

...似乎不起作用,很高兴您能在不对代码进行子类化(实际上我的代码已被过度子类化)或不使用装饰器的情况下向我展示我的概念错误或其他替代解决方案

...seems not to work, I'm glad if you can show me my concept error or other alternative solutions without subclassing the code (actually my code is already over-subclassed) or using decorators (this is the solution I'll use if there is no other).

谢谢。

推荐答案

属性使用描述符协议起作用,该协议仅对 class obj的属性起作用。该属性对象必须存储在类属性中。您不能在每个实例的基础上覆盖它。

Properties work using the descriptor protocol, which only works on attributes of a class object. The property object has to be stored in a class attribute. You can't "override" it on a per-instance basis.

当然,您可以在类上提供一个获取实例属性或后退的属性。设置为默认值:

You can, of course, provide a property on the class that gets an instance attribute or falls back to some default:

class C(object):
    _default_x = 5
    _x = None
    @property
    def x(self):
        return self._x or self._default_x
    def alpha(self, beta):
        self._x = beta

这篇关于在方法内使用Python property()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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