Python 应用同一属性装饰器的不同结果

Python 应用同一属性装饰器的不同结果,python,python-3.x,properties,Python,Python 3.x,Properties,当我将属性装饰器应用于类定义中的方法时,python接受具有@decorator但不具有显式语法的版本。代码如下: >>> class Person: ... first_name = property() ... def first_name(self): ... pass ... first_name = first_name.getter(first_name) ... Traceback (most recent call la

当我将
属性
装饰器应用于类定义中的方法时,python接受具有
@decorator
但不具有显式语法的版本。代码如下:

>>> class Person:
...     first_name = property()
...     def first_name(self):
...         pass
...     first_name = first_name.getter(first_name)
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in Person
AttributeError: 'function' object has no attribute 'getter'

我只做了语法上的修改,但这个版本没有错误。为什么?

在第一个示例中,您使用函数覆盖了
first\u name
中的属性。默认情况下,函数没有
getter
属性。
def
是一种语法糖(有点类似于):

first_name = property()

# def replacement
first_name = lambda self: None

first_name = first_name.getter(first_name)
第二个使用decorator,因此
first\u name
property().getter(func)
返回的内容。这是一种财产

尽管如此,所有这些的标准样式是:

@property
def first_name(self):
    pass
与以下内容大致相同:

first_name = property(lambda self: None)
getter/setter样式之所以有效,是因为在将函数分配给命名空间之前引用了decorator(事实上,在使用decorator时,没有将函数分配给命名空间的中间步骤)


我知道正常的风格——我正在阅读Python食谱中的一个例子。我不明白的是,我所说的两种方法在语法上是等价的,但产生不同的结果。当使用
@
时,为什么没有名称冲突?因为作为属性的
first\u name
在作为装饰程序的结果被覆盖之前被引用。按照惯例,我可以在getter之后使用setter方法
@first\u name.setter
。如果作为getter装饰器的结果,
first\u name
现在是一个修改过的方法名,那么setter语法将如何工作
first_name
现在不是
属性
对象。
@first\u name.setter
如何再次引用属性对象?
property.getter
property.setter
都返回属性。只要
first\u name
是一个开始的属性,那么就没有问题。我想
first\u name
在应用getter之后仍然是一个
属性。
first_name = property(lambda self: None)
first_name = property()
# this is effectively how the function definition and decorator code is executed
first_name = first_name.getter(lambda self: None)