Is it possible to have a function run at the beginning of every function of a class without explicitly writing it? I'm going to have a class with 20 or so methods, and though I can just copy and paste, I was wondering if there was an easier way to do things. Thanks in advance.
Mathhax0r 2 Junior Poster in Training
Recommended Answers
Jump to PostYes, you can, although its not that pretty, here is something that i think shows how something like that can be done.
class Example(object): #This is what we use to call every function def functionCaller(self, functionName): #This is the function that needs to #be called every time …
Jump to Postmmmm, i would use decorators as well... i was just thinking if you didnt want to have to type that
arbitraryFunction()
that you probably wouldn't want to type@arbitraryDecorator
That being said, decorators can be very useful and powerful especially when it comes to classes, so if you haven't used …
Jump to PostIt was a ***** to do, but I believe I figured out how to decorate each and every method in a class by decorating only the class itself.
def method_decorator(class_declaration): class NewClass(): pass for key in class_declaration.__dict__: if hasattr(class_declaration.__dict__[key], '__call__'): def new_method(*args, **kwargs): print("This is a decorator.") …
All 10 Replies

masterofpuppets
Mathhax0r 2 Junior Poster in Training
lllllIllIlllI 178 Veteran Poster
lrh9 95 Posting Whiz in Training
lllllIllIlllI 178 Veteran Poster
lrh9 95 Posting Whiz in Training
lrh9 95 Posting Whiz in Training
Gribouillis commented: A class decorator is the solution. +2
lrh9 95 Posting Whiz in Training
kriti98 0 Newbie Poster
lllllIllIlllI commented: Make a new thread +0
jcao219 18 Posting Pro in Training
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.