Skip to content

Instantly share code, notes, and snippets.

@zaltoprofen
Created July 27, 2018 00:50
Show Gist options
  • Select an option

  • Save zaltoprofen/e4b9ccd553b6a01a0734acc5e20f7631 to your computer and use it in GitHub Desktop.

Select an option

Save zaltoprofen/e4b9ccd553b6a01a0734acc5e20f7631 to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"_class_table = {}\n",
"class EntityMeta(type):\n",
" def __new__(mcs, name, bases, namespace):\n",
" cls = super().__new__(mcs, name, bases, namespace)\n",
" if 'name' in namespace:\n",
" _class_table[namespace['name']] = cls\n",
" return cls\n",
" \n",
" def __getitem__(self, key):\n",
" return _class_table[key]\n",
"\n",
"class Entity(metaclass=EntityMeta):\n",
" def __setattr__(self, key, value):\n",
" if '_fields' not in self.__dict__:\n",
" self.__dict__['_fields'] = []\n",
" self._fields.append(key)\n",
" super().__setattr__(key, value)\n",
" \n",
" def __str__(self):\n",
" fields = {n: getattr(self, n) for n in self._fields}\n",
" return f'<{self.__class__.__name__}: {fields}>'\n",
"\n",
"class Person(Entity):\n",
" name = 'person'\n",
" \n",
" def __init__(self, name, age):\n",
" self.name = name\n",
" self.age = age\n",
" \n",
" def greet(self):\n",
" print(f'Hello, {self.name}')\n",
"\n",
"class Plant(Entity):\n",
" name = 'plant'\n",
"\n",
" def __init__(self, name, binomen):\n",
" self.name = name\n",
" self.binomen = binomen"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<Person: {'name': 'Yuriko Nanao', 'age': 15}>\n",
"<Plant: {'name': '白樺', 'binomen': 'Betula platyphylla'}>\n"
]
}
],
"source": [
"print(Entity['person']('Yuriko Nanao', 15))\n",
"print(Entity['plant']('白樺', 'Betula platyphylla'))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.5"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment