码迷,mamicode.com
首页 > 编程语言 > 详细

python实现数组属性

时间:2015-02-17 12:55:47      阅读:289      评论:0      收藏:0      [点我收藏+]

标签:python

属性的简单用法

属性看起来像是对成员进行直接访问,但又可以像函数一样对成员访问进行其他处理,所以属性是一种兼具易用性和数据封装的语言设施。python定义属性的方式有很多种,下面是我认为最简单直接的一种:

class MyClass(object):
    def __init__(self):
        self._x = 10

    def get_x(self):
        return self._x
    def set_x(self, x):
        self._x = max(0, x)
    x = property(get_x, set_x)

使用代码:

mc = MyClass()
print mc.x
mc.x = 39
print mc.x

输出是:

10
39

实现数组属性

Delphi除了普通属性外,还有一种数组属性:

TMyClass = class(TObject)
private
  function Get(Index: Integer): Pointer;
  procedure Put(Index: Integer; Item: Pointer);
public
  property Items[Index: Integer]: Pointer read Get write Put;
end;

Items就像数组一样,可以用下标访问:

v1 = myclass.Items[2]
myclass.Items[1] = v2

利用python的语法特性,也可以实现类似的效果,这里用到Descriptor,关于这种语法特性,建议看这个文档:Descriptor HowTo Guide,下面就直接给出一个简略的代码:

class property_a(object):
    def __init__(self, fget=None, fset=None):
        self.fget = fget
        self.fset = fset
        self.obj = None
    def __get__(self, instance, owner):
        self.obj = instance
        return self
    def __getitem__(self, item):
        if self.fget is None:
            raise AttributeError("unreadable attribute")
        return self.fget(self.obj, item)
    def __setitem__(self, key, value):
        if self.fset is None:
            raise AttributeError("can‘t set attribute")
        self.fset(self.obj, key, value)

然后就可以像这样定义数组属性:

class MyClass(object):
    def __init__(self):
        self._a = [1, 2, 3]

    def get_a(self, index):
        return self._a[index]
    def set_a(self, index, value):
        self._a[index] = value
    a = property_a(get_a, set_a)

用法如下:

mc = MyClass()
print mc.a[1]
mc.a[1] = 39
print mc.a[1]

输出如下:

2
39

本人学习python不长,其中必有一些考虑不全的地方,欢迎高手指正

python实现数组属性

标签:python

原文地址:http://blog.csdn.net/linzhengqun/article/details/43865855

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!