Python setter装饰器如何工作 [英] How does the Python setter decorator work

查看:43
本文介绍了Python setter装饰器如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用Python,所以如果我遗漏了一些明显的东西,请多多包涵.我已经阅读了有关装饰器及其工作方式的信息,并试图了解其如何翻译:

I am just starting Python, so bear with me if I am missing something obvious. I have read about the decorators and how they work, and I am trying to understand how this gets translated:

class SomeObject(object):

    @property
    def test(self):
        return "some value"

    @test.setter   
    def test(self, value):
        print(value)

根据我的阅读,应该变成:

From what I have read, this should be turned into:

class SomeObject(object):

    def test(self):
        return "some value"

    test = property(test)

    def test(self, value):
        print(value)

    test = test.setter(test)

但是,当我尝试此操作时,我会得到

However when I try this, I get

AttributeError: 'function' object has no attribute 'setter'

有人可以解释这种情况下的翻译工作吗?

Can someone explain how the translation works in that case?

推荐答案

获得 AttributeError 的原因是 def test 重新定义了 test在类的范围内.类中的函数定义绝非特别.

The reason you're getting that AttributeError is that def test re-defines test in the scope of the class. Function definitions in classes are in no way special.

您的示例将像这样

class SomeObject(object):

    def get_test(self):
        return "some value"

    def set_test(self, value):
        print(value)

    test = property(get_test)
    test = test.setter(set_test)
    # OR
    test = property(get_test, set_test)

这篇关于Python setter装饰器如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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