问题
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