类属性
classpropert的Python项目详细描述
Author: | Philipp von Weitershausen |
---|---|
Email: | philikon@philikon.de |
License: | Zope Public License, v2.1 |
动机
使用方法修饰符和像property这样的描述符,我们可以 轻松创建计算属性:
>>> class JamesBrown(object): ... @property ... def feel(self): ... return self._feel
但是,这样的属性无法写入。你必须 这样做:
>>> class JamesBrown(object): ... def _getFeel(self): ... return self._feel ... def _setFeel(self, feel): ... self._feel = feel ... feel = property(_getFeel, _setFeel)
这种方法的问题是它离开了getter和setter 坐在类命名空间中。它也缺少紧凑型 装饰解决方案的拼写。为了应付这种情况,有些人喜欢 写入:
>>> class JamesBrown(object): ... @apply ... def feel(): ... def get(self): ... return self._feel ... def set(self, feel): ... self._feel = feel ... return property(get, set)
这个拼写感觉很麻烦,除了 apply在python 3000中是going to go away。
目标
应该有一种方法来声明读写属性并仍然使用 简洁易用的装饰拼写。读写属性 应该和只读属性一样易于使用。我们明确 我不想马上调用那个真正帮助我们的函数 命名属性并为getter和setter创建本地作用域。
类属性
类属性允许您通过^{tt3}定义属性$ 陈述。定义一个动态属性,就好像在实现 一个班。工作原理如下:
>>> from classproperty import classproperty >>> class JamesBrown(object): ... class feel(classproperty): ... def __get__(self): ... return self._feel ... def __set__(self, feel): ... self._feel = feel>>> i = JamesBrown() >>> i.feel Traceback (most recent call last): ... AttributeError: 'JamesBrown' object has no attribute '_feel'>>> i.feel = "good" >>> i.feel 'good'
当然,删除程序也是可能的:
>>> class JamesBrown(object): ... class feel(classproperty): ... def __get__(self): ... return self._feel ... def __set__(self, feel): ... self._feel = feel ... def __delete__(self): ... del self._feel>>> i = JamesBrown() >>> i.feel = "good" >>> del i.feel >>> i.feel Traceback (most recent call last): ... AttributeError: 'JamesBrown' object has no attribute '_feel'