如何定义class内的装饰器?

How to define decorator within the class?

我想在 class 中使用装饰器,但出现位置错误。 1.I 不想使用函数工具和导入包装。 2.Can 我们在 class 中声明它而不是在 class 之外定义装饰器? 还有其他方法可以在 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)

如果我在 class 中初始化 u,v 并通过 t1 调用它并在诸如 check 之类的方法中使用它,它会给出一个错误,指出术语有位置参数错误。

如果我在实例 t1 中初始化 u,v 并通过 t1.video1 调用它并在诸如 check 之类的方法中使用它,它会给出一个错误,指出视频没有位置参数“v”。

如何使用装饰器?请大家帮帮我。

这里只是给你举个例子,(根据你的需要修改)-

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'

此外,您正在打印类似

的对象
t1 = term()
t1.video1(u,v)
print(t1)

但是,你应该像这样打印 -

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