We can easily create decorators inside a class and it is easily accessible for its child classes. During Decorator creation, we must take care that the function that we are defining inside the decorator must take current object reference (self) as a parameter, and while we are accessing that decorator from child class that time we must call that decorator using the class name(class in which Decorator is present).
Example 1: Here in this example we are creating a decorator function inside Class A. Inside Class A “fun1” Instance Method is calling the decorator function “Decorators” inside Class B “fun2”. Instance Method is calling the decorator function of Class A. To use the decorator of Class A, we must require using Class name in which decorator is present that’s why we use “@A.Decorators” here.
Decoration started. Decorating - Class A methods. Decoration of function completed. Decoration started. Decoration - Class B methods. Decoration of function completed.
Example 2: Checking number is Even or Odd using Decorator.
User Input : 45 No, it's ODD Number. User Input : 2 Yes, it's EVEN Number. User Input : 7 No, it's ODD Number.
Example 3: Checking Grade from Marks.
Your Score : 89 Grade : A Your Score : 34 Grade : F
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.