解决报错:在Python中使用property装饰器时,出现错误:TypeError: descriptor ‘setter‘ requires a ‘property‘ object but(代码片

Posted 温柔且上进c

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了解决报错:在Python中使用property装饰器时,出现错误:TypeError: descriptor ‘setter‘ requires a ‘property‘ object but(代码片相关的知识,希望对你有一定的参考价值。

错误信息

       •我们在使用property装饰器时,可能因为装饰器名称书写错误导致下述错误:

TypeError: descriptor 'setter' requires a 'property' object but received a 'function'

问题分析

       •出现此错误的原因是我们将所有的装饰器名称都写为了property,而不是我们的类中相同的方法名:

问题代码

class AgeDemo(object):

    def __init__(self, age):
        self.age = age

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

    @property.setter   # 出现问题的代码行
    def age_test(self, age):
        if not isinstance(age, int):
            raise TypeError('TypeError')
        self.age = age

解决报错

       •将图中出现报错的装饰器名称改为我们类中设置的相同名称,即可解决此报错!!!
代码如下:

class AgeDemo(object):

    def __init__(self, age):
        self.age = age

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

    @age_test.setter # 修改的代码行
    def age_test(self, age):
        if not isinstance(age, int):
            raise TypeError('TypeError')
        self.age = age

参考文档

       •其它关于python装饰器的问题可参考官方文档:python装饰器官方文档!!!

以上是关于解决报错:在Python中使用property装饰器时,出现错误:TypeError: descriptor ‘setter‘ requires a ‘property‘ object but(代码片的主要内容,如果未能解决你的问题,请参考以下文章

Python装饰器之 property()

二十三Python 中 property() 函数及 @property 装饰器的使用

Python中,关于@property装饰器

Python中的property类和@property装饰器

python面向对象:组合封装property装饰器多态

Python使用@property装饰器--getter和setter方法变成属性