Python进阶之“属性(property)”详解
2017-03-16 16:35
525 查看
Python中有一个被称为属性函数(property)的小概念,它可以:
将类方法转换为只读属性
class Person(object):
""""""
#----------------------------------------------------------------------
def
__init__(self,
first_name,
last_name):
"""Constructor"""
self.first_name
= first_name
self.last_name
= last_name
#----------------------------------------------------------------------
@property
def
full_name(self):
"""
Return the full name
"""
return
"%s %s" %
(self.first_name,
self.last_name)
在上面的代码中,我们创建了两个类属性:self.first_name和self.last_name。接下来,我们创建了一个full_name方法,它有一个@property装饰器。这使我们能够在Python解释器会话中有如下的交互:
>>>
person =
Person("Mike",
"Driscoll")
>>> person.full_name
'Mike Driscoll'
>>> person.first_name
'Mike'
>>> person.full_name
= "Jackalope"
Traceback
(most recent
call last):
File
"<string>",
line 1,
in <fragment>
AttributeError:
can't
set attribute
正如你所看到的,因为我们将方法变成了属性,我们可以使用正常的点符号访问它。但是,如果我们试图将该属性设为其他值,我们会引发一个AttributeError错误。改变full_name属性的唯一方法是间接这样做:
>>>
person.first_name
= "Dan"
>>> person.full_name
'Dan Driscoll'
将类方法转换为只读属性
class Person(object):
""""""
#----------------------------------------------------------------------
def
__init__(self,
first_name,
last_name):
"""Constructor"""
self.first_name
= first_name
self.last_name
= last_name
#----------------------------------------------------------------------
@property
def
full_name(self):
"""
Return the full name
"""
return
"%s %s" %
(self.first_name,
self.last_name)
在上面的代码中,我们创建了两个类属性:self.first_name和self.last_name。接下来,我们创建了一个full_name方法,它有一个@property装饰器。这使我们能够在Python解释器会话中有如下的交互:
>>>
person =
Person("Mike",
"Driscoll")
>>> person.full_name
'Mike Driscoll'
>>> person.first_name
'Mike'
>>> person.full_name
= "Jackalope"
Traceback
(most recent
call last):
File
"<string>",
line 1,
in <fragment>
AttributeError:
can't
set attribute
正如你所看到的,因为我们将方法变成了属性,我们可以使用正常的点符号访问它。但是,如果我们试图将该属性设为其他值,我们会引发一个AttributeError错误。改变full_name属性的唯一方法是间接这样做:
>>>
person.first_name
= "Dan"
>>> person.full_name
'Dan Driscoll'
相关文章推荐
- Python进阶之“属性(property)”详解
- Python进阶之“属性(property)”详解
- Python内置函数进阶之“属性(property())”详解
- Python进阶之“属性(property)”详解
- Python进阶之“属性(property)”详解
- Python进阶之属性(property)详解
- Python进阶之“属性(property)”详解
- Python进阶之“属性(property)”详解
- Python进阶之“属性(property)”详解
- Python进阶之“属性(property)”详解
- python 进阶之属性函数property
- Python中用Descriptor实现类级属性(Property)详解
- Python中用Descriptor实现类级属性(Property)详解
- Python “属性(property)”详解
- Python 类之 “属性(property ) "详解
- python 属性 property、getattr()、setattr()详解
- python学习-面向对象进阶之属性property(七)
- python进阶教程之动态类型详解
- python property属性
- python进阶教程之动态类型详解