类属性

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 for(inti:x)做什么?   java如何将一个bean的构造函数参数传递给嵌套bean   java从易趣链接提取项目ID   java多线程BufferedReader   安卓全新应用程序在R.java中抛出“语法错误,插入“}”以完成类体”   java Spring启动依赖注入请求范围的bean   java给定的时间,然后约定和异常处理。和莫基托和朱尼特在一起   与Android Studio的java Oracle数据库连接   在web服务器(Heroku)上承载可运行jar文件(Discord bot)的java   java如何每隔n秒在imageview中更改图像   java不理解“volatile”关键字   java使用JPA编写自定义SQL查询   java如何使用filechannel作为参数来编写对象