lundi 10 décembre 2018

What is correct decorator design pattern implementation in Python?

I am having some subclasses which have some parallel attributes and I want to use the decorator pattern to deal with, so that I could simple build different graph with simple isinstance syntax. I referred to this post.

My test code(Py27) is like:

import inspect 

class Cls_Base(object):
    def __init__(self, n):
        self.number = n
    def __str__(self):
        return '{}, {}'.format(self.number,self.__class__.__name__)

class Ext_c1(Cls_Base):
    def __init__(self):
        self.pos=self.number+3
    def __str__(self):
        return '{}, {}'.format(self.pos,self.__class__.__name__)

class Ext_c2(Cls_Base):
    def __init__(self):
        pass
    def __str__(self):
        return '{}, {}'.format(self.number+1,self.__class__.__name__)

class Cls_Decorator(Cls_Base):
    def __new__(cls, decoratee, c):
        cls_name=c if inspect.isclass(c) else globals()[c]
        cls = type(cls_name.__name__,
                   (cls_name, decoratee.__class__),
                   decoratee.__dict__)
        return object.__new__(cls) 

base=Cls_Base(1)
c1=Cls_Decorator(base,Ext_c1)
c1_2=Cls_Decorator(c1,Ext_c2)
c2=Cls_Decorator(base,Ext_c2)

When examining the value and method of c1, c1_2, c2, the results turn to be:

>>> base.__dict__
{'number': 1}
>>> c1.__dict__
{}
>>> c2.__dict__
{}
>>> c1_2.__dict__
{}
>>> str(c1)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "test_cls.py", line 17, in __str__
    return '{}, {}'.format(self.pos,self.__class__.__name__)
AttributeError: 'Ext_c1' object has no attribute 'pos'
>>> str(c2)
'2, Ext_c2'
>>> str(base)
'1, Cls_Base'
>>> str(c1_2)
'2, Ext_c2'
>>> c1.__init__()
>>> str(c1)
'4, Ext_c1'
>>> c1.__dict__()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: 'dict' object is not callable
>>> c1.__dict__
{'pos': 4}

See, overloaded and inherited methods work well. But the decorator fails to initiate class dict due to no initiator is called before new space allocated. What I could do to avoid explicitly using __init__() outside the class? Or is there some more elegant way to do equivalent jobs?

Aucun commentaire:

Enregistrer un commentaire