airportyh / misc

Toby's random stuff

This URL has Read+Write access

misc / prototype.py / prototype.py
100644 69 lines (56 sloc) 1.839 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import new
import inspect
 
def _getattr(obj, name):
    try:
        return object.__getattribute__(obj, name)
    except AttributeError:
        return None
 
def _setattr(obj, name, val):
    object.__setattr__(obj, name, val)
 
def _proto_getattr(obj, name):
    val = _getattr(obj, name)
    if val is None:
        parent = _getattr(obj, '__proto__')
        val = _getattr(parent, name)
    return val
 
class ObjectMetaClass(type):
    def __repr__(cls):
        return "<constructor '%s'>" % cls.__name__
 
class Object(object):
    __metaclass__ = ObjectMetaClass
    prototype = None
    
    def __init__(this):
        this.__proto__ = this.prototype
        this.constructor = this.__class__
    
    def __getattribute__(this, name):
        val = _proto_getattr(this, name)
        if isinstance(val, property) and val.fget:
            get = new.instancemethod(val.fget, this)
            return get()
        elif inspect.isfunction(val):
            func = new.instancemethod(val, this)
            return func
        else:
            return val
            
    def __setattr__(this, name, val):
        if not isinstance(val, property):
            _val = _proto_getattr(this, name)
            if isinstance(_val, property) and _val.fset:
                _val.fset(this, val)
                return
        _setattr(this, name, val)
 
    def __delattr__(this, name):
        val = _proto_getattr(this, name)
        if isinstance(val, property) and val.fdel:
            val.fdel(this)
        else:
            object.__delattr__(this, name)
 
Object.prototype = Object()
 
def constructor(func):
    ret = type(func.__name__, (Object,), dict())
    ret.prototype = ret()
    def init(this, *vargs, **kwargs):
        Object.__init__(this)
        func(this, *vargs, **kwargs)
    ret.__init__ = init
    return ret