Pylint:如何用属性类指定自定义的属性装饰器?

时间:2018-07-03 18:31:15

标签: python properties pylint

Pylint针对使用自定义属性装饰器的Python代码报告错误E0202(隐藏方法)。我尝试使用property-classes选项失败。

这里是props.py

from functools import wraps

def myproperty(func):
    @wraps(func)
    def fget(self):
        return func(self)
    return property(fget)

testimport.py

#!/usr/bin/python

from props import myproperty

class E0202(object):

    def __init__(self):
        self._attr = 'attr'
        self._myattr = 'myattr'

    @property
    def attr(self):
        return self._attr

    @attr.setter
    def attr(self, value):
        self._attr = value

    @myproperty
    def myattr(self):
        return self._myattr

    @myattr.setter
    def myattr(self, value):
        self._myattr = value

    def assign_values(self):
        self.attr = 'value'
        self.myattr = 'myvalue'

if __name__ == '__main__':
    o = E0202()
    print(o.attr, o.myattr)
    o.assign_values()
    print(o.attr, o.myattr)

使用Python 2.7.13运行代码会产生预期的结果:

$ python test.py
('attr', 'myattr')
('value', 'myvalue')

Pylint 1.6.5报告自定义属性的错误,而不是常规属性的错误:

$ pylint -E --property-classes=props.myproperty testimport.py 
No config file found, using default configuration
************* Module testimport
E: 20, 4: An attribute defined in testimport line 29 hides this method (method-hidden)

第29行是自定义属性的设置方法的使用:

        self.myattr = 'myvalue'

pylint的正确选择是什么?还是误报?

1 个答案:

答案 0 :(得分:1)

不确定是否遇到与您相同的问题,因为我遇到了no-member错误。

我使用的装饰器名为@memoized_property,通过将其添加到pylintrc中,我得以解决该问题:

init-hook="import astroid.bases; astroid.bases.POSSIBLE_PROPERTIES.add('memoized_property')"

(您也可以将其作为参数传递给pylint:--init-hook="import astroid.bases; astroid.bases.POSSIBLE_PROPERTIES.add('memoized_property')“)