Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:如何访问装饰类';是否从类装饰器内部创建实例?_Python_Decorator - Fatal编程技术网

Python:如何访问装饰类';是否从类装饰器内部创建实例?

Python:如何访问装饰类';是否从类装饰器内部创建实例?,python,decorator,Python,Decorator,这里有一个例子来说明我的意思: class MyDecorator(object): def __call__(self, func): # At which point would I be able to access the decorated method's parent class's instance? # In the below example, I would want to access from here: myinstan

这里有一个例子来说明我的意思:

class MyDecorator(object):    
    def __call__(self, func):
        # At which point would I be able to access the decorated method's parent class's instance?
        # In the below example, I would want to access from here: myinstance
        def wrapper(*args, **kwargs):
            return func(*args, **kwargs)
        return wrapper

class SomeClass(object):
    ##self.name = 'John' #error here
    name="John"

    @MyDecorator()
    def nameprinter(self):
        print(self.name)

myinstance = SomeClass()
myinstance.nameprinter()

我需要修饰实际的类吗?

请注意,在此上下文中,“self”的使用只是一种约定,方法只使用第一个参数作为对实例对象的引用:

class MyDecorator(object):
    def __call__(self, func):
      def wrapper(that, *args, **kwargs):
        ## you can access the "self" of func here through the "that" parameter
        ## and hence do whatever you want        
        return func(that, *args, **kwargs)
      return wrapper
class Example:
  def __init__(foo, a):
    foo.a = a
  def method(bar, b):
    print bar.a, b

e = Example('hello')
e.method('world')

自参数作为第一个参数传递。您的
MyDecorator
也是一个模拟函数的类。更容易使其成为实际功能

def MyDecorator(method):
    def wrapper(self, *args, **kwargs):
        print 'Self is', self
        return method(self, *args, **kwargs)
    return wrapper

class SomeClass(object):
    @MyDecorator
    def f(self):
       return 42

print SomeClass().f()

self.name='John'
。。。那是什么?谢谢你的回答,但那不是我要问的。我希望从类装饰器内部访问类实例。检查一下杜邦的答案。我喜欢旧答案解决新问题!谢谢你的花絮!