类属性

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'

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
(数组)列出Java中的实现   java检测JDBC连接中尚未提交的开放事务   java H2语句池   java正在使用cardlayout,有一个我无法解决的问题   java Android MTP客户端打开的是整个设备,而不是单个接口   java Querydsl mongodb gradle springboot问题   java XML使用外部xsd验证anytype类型的XML的一部分   java如何使用Hibernate在实体中创建属性表?   intellij理念“BufferedReader”与“java.io.BufferedReader”之比较。这有关系吗?   java解释多线程的输出   Eclipse中的java Android应用程序:编辑未显示在图形布局上的文本   java如何在struts 1中使用显示标记?