Home > Article > Backend Development > How to decorate a class in Python?
It uses additional Python statements to modify the old object and return the same reference.
For example, consider the following class, which has two methods: __init__ and display. The __init__ method initializes the name variable when displaying the output name:
class Student: def __init__(self, name): self.name = name def display(self): print('Name:', self.name)
To decorate this class in Python, we can add new methods to the class or modify existing methods, or both.
Also, there are two ways to do this in Python, either using a function decorator or a class decorator.
Let’s look at the examples one by one.
To use a function decorator to decorate a class, accept the class as a parameter, modify its code and return the class at the end.
def mydecorator(student): #define a new display method def newdisplay(self): print('Name: ', self.name) print('Subject: Programming') #replace the display with newdisplay student.display = newdisplay #return the modified student return student @mydecorator class Student: def __init__(self, name): self.name = name def display(self): print('Name:', self.name) obj = Student('Pencil Programmer') obj.display() ''' Name: Pencil Programmer Subject: Programming '''
If the display method does not exist in the class, newdisplay will be added to the class as a display method.
To decorate a class using a class decorator, accept a reference to the class as a parameter (in the decorator's __init__ method), in __call__ Modify its code in the method, and finally return an instance of the modified class.
class Mydecorator: #accept the class as argument def __init__(self, student): self.student = student #accept the class's __init__ method arguments def __call__(self, name): #define a new display method def newdisplay(self): print('Name: ', self.name) print('Subject: Python') #replace display with newdisplay self.student.display = newdisplay #return the instance of the class obj = self.student(name) return obj @Mydecorator class Student: def __init__(self, name): self.name = name def display(self): print('Name: ', self.name) obj = Student('Pencil Programmer') obj.display() ''' Name: Pencil Programmer Subject: Python '''
The only difference here is that we return an object reference instead of a class reference.
Original text:https://www.php.cn/link/137ffea9336f8b47a66439fc34e981ee
The above is the detailed content of How to decorate a class in Python?. For more information, please follow other related articles on the PHP Chinese website!