When using the DDD repository pattern and context map, I wanted to give dynamic behavior to the instance, so I investigated how to realize DCI (Data Context Interaction) in Python.
DCI in Python Python DCI package that seems to have been born from thread
It's rather old and unpopular, but it's well done.
class Person(object):
def __init__(self, name):
self.name = name
from roles import RoleType
class Carpenter(object):
__metaclass__ = RoleType
def chop(self):
return "chop, chop"
If you define Person and Carpenter like
>>> person = Person("John")
>>> Carpenter(person)
<Person+Carpenter object at 0x...>
You can give a Person instance the behavior of a Carpenter.
Dynamic Mixin
Implemented a function that dynamically adds the attributes of the Mixin class to the instance.
import types
def mixin(instance, mixin_class):
"""Dynamic mixin of methods into instance - works only for new style classes"""
for name in mixin_class.__dict__:
if name.startswith('__') and name.endswith('__') \
or not type(mixin_class.__dict__[name])==types.FunctionType:
continue
instance.__dict__[name]=mixin_class.__dict__[name].__get__(instance)
class Person(object):
def __init__(self, name):
self.name = name
class CarpenterMixin(object):
def chop(self):
return "chop, chop"
As defined as
>>> person = Person("John")
>>> mixin(person, CarpenterMixin)
>>> person.chop()
'chop, chop'
It's relatively easy. Dynamic Mixin (2)
An aggressive way to dynamically rewrite the inheritance tree of a class of instance. The explanation is omitted. Please see the link.
I think it may be possible to give up giving behavior to the instance itself and realize it with Delegation.
I have greatly referred to the following pages.
-About Service and DCI ~ Where should the behavior be ~ -Reply to "You can use Service just because DCI is troublesome" -[Impressions and poems after reading "Response to" DCI is just a hassle to use Service "" (https://gist.github.com/monzou/8eaf32f1f8fda92e18e3)
Recommended Posts