shaila
shaila

Reputation: 335

How to define decorator within the class?

I wanted to use decorator inside a class but I am getting positional error. 1.I dont want to use functools and import wraps. 2.Can we declare it within the class rather than defining decorator outside class? Is there any other method to declare a decorator within a class?

from pytube import YouTube

if __name__ == "__main__":
    class term :
        # def __init__(self,u,v):
        #     self.url = u
        #     self.path = v

        def check(func):
            def parameters(self,u,v):
                print(f"title:{YouTube(u).title}, views:{YouTube(u).views}, Length:{YouTube(u).length}")
                func(u,v)
                print("Yes done")
            return parameters
        # return check

        @check
        def video1(self,u,v):
            # y = YouTube(u)
            # print("Y is",y) 
            video1 = YouTube(u).streams.first().download(v)
            print("Success") 
            return video1

u = input("Enter the video URL: ")
v = input("Enter the path: ")

t1 = term()
t1.video1(u,v)
print(t1)

If I initialise u,v inside class and call it via t1 and use it in methods like check it gives an error saying term has positional argument error.

If I initialise u,v inside instance t1 and call it via t1.video1 and use it in methods like check it gives an error saying video has no positional argument "v".

How to use decorators?Can you pls help me.

Upvotes: 0

Views: 67

Answers (1)

Suyog Shimpi
Suyog Shimpi

Reputation: 866

Here is just an example for you, (Modify as per your need) -

class term:

    def check(func):
        def parameters(self, u, v):
            print(f"title:")
            print("Yes done")
            return func(self, u, v)
        return parameters

    @check
    def video1(self, u, v):
        print("Success")
        return 'Hello'

Also, You are printing an object like

t1 = term()
t1.video1(u,v)
print(t1)

But, you should be printing like -

t1 = term()
result = t1.video1(u,v)
print(result)

Upvotes: 2

Related Questions