How does the Python setter decorator work

可紊 提交于 2019-12-23 16:49:21

问题


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?


回答1:


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.

Your example would work like this

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)


来源:https://stackoverflow.com/questions/10381967/how-does-the-python-setter-decorator-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!