【问题标题】:Class as decorators and scope of a function over the element in the class, in python类作为装饰器和类中元素的函数范围,在python中
【发布时间】:2018-09-23 09:40:58
【问题描述】:

在函数上使用类装饰器时,函数如何访问类中的 self._count 元素。我知道装饰器需要一个可调用对象并返回一个可调用对象。但是函数可以对类装饰器的内部元素有作用域吗?

class decorate_class:
    def __init__(self, f):
        self._func = f
        self._count = 0

    def __call__(self, *args, **kargs):
        self._count += 1
        return self._func(*args, **kargs)

@decorate_class
def callname(name):
    print("Hello, {0}".format(name))

现在,当我使用参数调用函数时,我应该跟踪正在调用的次数。但我不明白的是,callname 函数如何访问 self._count?

callname('Abhishek') # o/p --> Hello, Abhishek
callname('Ashley') # o/p --> Hello, Ashley
callname._count # o/p --> 2 ( But how can callname access _count?)

有人可以帮我理解这个吗?特别是范围。

【问题讨论】:

  • 但是我可以访问它。上面的代码是有效的。我也得到了输出 2。我想知道它的作用域如何?
  • Callname._count 返回 2

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


【解决方案1】:

如示例:

class decorate_class:
    def __init__(self, f):
        self._func = f
        self._count = 0

    def __call__(self, *args, **kargs):
        self._count += 1
        return self._func(*args, **kargs)

@decorate_class
def callname(name):
   print("Hello, {0}".format(name))


callname('bobo')
callname('dodo')
callname('will return 3')
print('It returns ->> ', callname._count)

结果:

Hello, bobo
Hello, dodo
Hello, will return 3
It returns ->>  3

说明

当你装饰你的函数时,你基本上每次都通过传递你的函数 callname 来调用 decorate_class,并且在调用实例时调用 __call__ 方法,它在内存中保存 _count 你r callname 函数继承自 __init__

我希望现在更清楚:)

【讨论】:

  • 这是否意味着 callname 函数将继承类中存在的任何属性?
  • 基本上是的,但是如果它是 Pythonic 的做法,我不能告诉你 :)
猜你喜欢
  • 2020-01-14
  • 1970-01-01
  • 2021-07-16
  • 2021-11-26
  • 2010-12-19
  • 2021-04-12
  • 1970-01-01
  • 2011-06-06
  • 2011-09-30
相关资源
最近更新 更多