In Python 2.5, is there a way to create a decorator that decorates a class? Specifically, I want to use a decorator to add a member to a class and change the constructor to take a value for that member.
Looking for something like the following (which has a syntax error on "class Foo:":
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()
I guess what I"m really after is a way to do something like a C# interface in Python. I need to switch my paradigm I suppose.
Apart from the question whether class decorators are the right solution to your problem:
In Python 2.6 and higher, there are class decorators with the @-syntax, so you can write:
@addID class Foo: pass
In older versions, you can do it another way:
class Foo: pass Foo = addID(Foo)
Note however that this works the same as for function decorators, and that the decorator should return the new (or modified original) class, which is not what you"re doing in the example. The addID decorator would look like this:
def addID(original_class): orig_init = original_class.__init__ # Make copy of original __init__, so we can call it without recursion def __init__(self, id, *args, **kws): self.__id = id self.getId = getId orig_init(self, *args, **kws) # Call the original __init__ original_class.__init__ = __init__ # Set the class" __init__ to the new one return original_class
You could then use the appropriate syntax for your Python version as described above.
But I agree with others that inheritance is better suited if you want to override
Spark is one of the hottest technologies in big data analysis right now, and with good reason. If you work for, or you hope to work for, a company that has massive amounts of data to analyze, Spark of...
Python Workout isn’t designed to teach you Python, although I hope and expect that you’ll learn quite a bit along the way. It is meant to help you improve your understand- ing of Python and how to...
Python for Programmers: with Big Data and Artificial Intelligence Case Studies This book, written for programmers with a high-level experience in another language, uses how-to instructions to teach...
Google BigQuery: The Definitive Guide PDF download. Data Warehousing, Analytics, and Machine Learning at Scale, 1st Edition, 2019. Work with petabyte-scale datasets while building a collaborative a...