/
telnov.ob
/
500lines
Обзор
Документация
Войти
/
telnov.ob
/
500lines
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
objmodel/code/02-attr-based/objmodel.py
94 строки
3 KB
Michael DiBernardo
Project format.
16 июл 2015, 14:43
16 июл 2015, 14:43
28ba1d6
Код
Авторство
О чём код?
MISSING = object() class Base(object): """ The base class that all of the object model classes inherit from. """ def __init__(self, cls, fields): """ Every object has a class. """ self.cls = cls self._fields = fields def read_attr(self, fieldname): """ read field 'fieldname' out of the object """ result = self._read_dict(fieldname) if result is not MISSING: return result result = self.cls._read_from_class(fieldname) if _is_bindable(result): return _make_boundmethod(result, self) if result is not MISSING: return result raise AttributeError(fieldname) def write_attr(self, fieldname, value): """ write field 'fieldname' into the object """ self._write_dict(fieldname, value) def isinstance(self, cls): """ return True if the object is an instance of class cls """ return self.cls.issubclass(cls) def callmethod(self, methname, *args): """ call method 'methname' with arguments 'args' on object """ meth = self.read_attr(methname) return meth(*args) def _read_dict(self, fieldname): """ read an field 'fieldname' out of the object's dict """ return self._fields.get(fieldname, MISSING) def _write_dict(self, fieldname, value): """ write a field 'fieldname' into the object's dict """ self._fields[fieldname] = value def _is_bindable(meth): return callable(meth) def _make_boundmethod(meth, self): def bound(*args): return meth(self, *args) return bound class Instance(Base): """Instance of a user-defined class. """ def __init__(self, cls): assert isinstance(cls, Class) Base.__init__(self, cls, {}) class Class(Base): """ A User-defined class. """ def __init__(self, name, base_class, fields, metaclass): Base.__init__(self, metaclass, fields) self.name = name self.base_class = base_class def method_resolution_order(self): """ compute the method resolution order of the class """ if self.base_class is None: return [self] else: return [self] + self.base_class.method_resolution_order() def issubclass(self, cls): """ is self a subclass of cls? """ return cls in self.method_resolution_order() def _read_from_class(self, methname): for cls in self.method_resolution_order(): if methname in cls._fields: return cls._fields[methname] return MISSING # set up the base hierarchy like in Python (the ObjVLisp model) # the ultimate base class is OBJECT OBJECT = Class(name="object", base_class=None, fields={}, metaclass=None) # TYPE is a subclass of OBJECT TYPE = Class(name="type", base_class=OBJECT, fields={}, metaclass=None) # TYPE is an instance of itself TYPE.cls = TYPE # OBJECT is an instance of TYPE OBJECT.cls = TYPE