在Python中模拟类型

时间:2016-12-12 17:56:17

标签: python operator-overloading python-descriptors

我正在开发一个从卡上读取字节码的智能卡应用程序。

我想要一个<A>Field()类,它应该代表一个保存<type 'A'>数据的字段,用字节码值实例化,我想尽可能自然地操作。

#ex.: to instatiate a new IntField with value 31611

IntField([0, 0, 123, 123])

我想到了这样的事情:

class IntField(object):

    value = None
    bytecode = []

    def __init__(self, bytecode):
        self.bytecode = bytecode
        # decodes bytecode to int
        self.decode()

    def __get__(self):
        return self.value

    def __set__(self, value):
        self.value = value
        # encodes new value into bytecode
        self.encode()

    # magic methods to opperate with int

    def some_behavior(self):
        print 'some_behavior'

    def decode(self):
        # applies decoding
        self.value = new_value

    def encode(self):
        # applies encoding
        self.bytecode = new_bytecode

所以我可以使用下面的内容:

>>> a = IntField([0, 0, 0, 3])
>>> print a
3
>>> a.some_behavior()
some_behavior
>>> print type(a)
<class '__main__.IntField'>
>>> a = 4 + a
>>> print a
7
>>> print type(a)
<class '__main__.IntField'>
>>> a.some_behavior()
>>> a = 23
>>> print a.bytecode
[0, 0, 0, 17]
>>> print type(a)
<class '__main__.IntField'>

我知道这可以像我看到的那样implementations of the concept。但是他们会降到C级才能实现。有没有更简单,纯粹的python方式这样做?我怎样才能做到这一点?

0 个答案:

没有答案