【问题标题】:How to define decorator within the class?如何在类中定义装饰器?
【发布时间】:2021-11-10 05:47:18
【问题描述】:

我想在类中使用装饰器,但出现位置错误。 1.我不想使用 functools 和 import wraps。 2.我们可以在类内声明而不是在类外定义装饰器吗? 还有其他方法可以在类中声明装饰器吗?

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)

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

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

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

【问题讨论】:

  • 请添加您遇到的错误的回溯。
  • 你需要在func(self, u,v)这样的方法中传递self

标签: python python-3.x decorator python-decorators


【解决方案1】:

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

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)

【讨论】:

  • 我为什么要再次为 t1 创建一个对象? @Suyog Shimpi
  • 如果您想在某处存储值,这就是我将其存储在变量 result = t1.video1(u,v) 中的原因。否则,您也可以使用print(t1.video1(u,v))
猜你喜欢
  • 2015-10-23
  • 1970-01-01
  • 1970-01-01
  • 2012-04-11
  • 1970-01-01
  • 2013-02-06
  • 2015-06-18
  • 2011-07-25
  • 1970-01-01
相关资源
最近更新 更多