存在属性时__init__之外的属性

时间:2017-06-24 22:50:42

标签: python properties attributes

Pylint告诉我,我将_age设置在__init__之外,这在风格上并不好,我明白为什么。但是,如果我使用属性来确保在某个间隔内设置我的属性,那么在属性设置器中设置属性是有意义的。我如何调和这两种相反的想法?

class Person:
    def __init__(self, age, height, weight):
        self.age = age

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, age):
        if 18 <= age <= 81:
            self._age = age
        else:
            raise ValueError('You are either too old or too young')

2 个答案:

答案 0 :(得分:3)

您并非真正正确实施getter / setter。您应该在init中执行的操作实际上是设置self._age = age

def __init__(self, age, height, weight):
    self._age = age

通过这种修正,现在根据您的设计,事情会按预期运作:

p = Person(1, 2, 3)
p.age = 10

输出:

ValueError: You are either too old or too young

非例外:

p = Person(1, 20, 3)
p.age = 22
age = p.age
print(age)

输出:22

答案 1 :(得分:2)

很明显,idjaw给出的答案误解了代码的设计,跳过了他尝试将“年龄”设置为1时应引发的异常。

pylint异常似乎是从未解决过的known issue。最好的选择就是直接使用# pylint: disable=attribute-defined-outside-init

相关问题