类属性

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类。forName在尝试连接到MySQL数据库时不起作用   java如何实现适配器模式(或针对以下情况的更具说服力的解决方案)?   Java中的多态性问题   带有@SecondaryTable注释的java JPA/Hibernate映射   java是否有JList的延迟加载实现?   java在nTested列表中查找元素并按特定属性删除   java将多个标记设置为“我的应用”中的内置地图应用   如何在使用java使用WebDriver创建新的google帐户时读取图像框中的文本   java返回的hashmap值为空   java我可以在应用服务器之外使用JBoss JDBC适配器吗?   java如何检查正在执行的类   java如何在打印文本字符串时使用Thymeleaf忽略HTML标记?   java如何调用泛型类型为T[]的方法作为参数?   索引如何使用java api中的solr 7.7.2在windows中索引文件夹中的txt文件?   java Akka:在子演员完成后停止演员   java JavaFX:无效的属性错误   我们可以使用java从MySql数据库中获取添加的图像吗?   java Swagger示例参数值   java如何解决:没有类型可用的源代码。您是否忘记继承所需的模块?   java为什么有前缀/后缀++但没有前缀/后缀+=?