Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I want to know that is there a way to create a decorator that decorates a class in Python 2.5? Particularly, I want to use a decorator to add a feature to a class and modify the constructor to take a value for that member.

Looking for something like the following:

def getId(self): return self.__id

class addID(original_class):

    def __init__(self, id, *args, **kws):

        self.__id = id

        self.getId = getId

        original_class.__init__(self, *args, **kws)

@addID

class Foo:

    def __init__(self, value1):

        self.value1 = value1

if __name__ == '__main__':

    foo1 = Foo(5,1)

    print foo1.value1, foo1.getId()

    foo2 = Foo(15,2)

    print foo2.value1, foo2.getId()

1 Answer

0 votes
by (108k points)

I assume you are talking about the metaclass. In a metaclass, the __new__ method is been passed as the full proposed definition of the class, which it can then revise before the class is built. You can, sub out the constructor for a new one.

Example:

def substitute_init(self, id, *args, **kwargs):

    pass

class FooMeta(type):

    def __new__(cls, name, bases, attrs):

        attrs['__init__'] = substitute_init

        return super(FooMeta, cls).__new__(cls, name, bases, attrs)

class Foo(object):

    __metaclass__ = FooMeta

    def __init__(self, value1):

        pass

Want to learn more concepts related to Python? Join this Python Course by Intellipaat.

Related questions

0 votes
1 answer
asked Nov 22, 2020 in Python by ashely (50.2k points)
0 votes
4 answers
0 votes
1 answer
asked Jul 14, 2020 in Python by ashely (50.2k points)
0 votes
4 answers

Browse Categories

...