0

我想这样做(虚拟示例):

def func():
    nonlocal var
    print (var)

class A:
    var = 'hola'
    func()

但我得到:“SyntaxError: no binding for nonlocal 'var' found”

如果该方法被修饰,我真正打算做的是将方法名称附加到类范围内的列表中。像这样的东西:

def decorator(func):
    nonlocal decorated
    decorated.append(func.__name__)
    return func

class A:
    decorated = []
    @decorate
    def f(self):
        pass
4

4 回答 4

2

使用装饰器标记函数,然后装饰为返回所有装饰函数的类方法。

import inspect

def decorate(func):
    func.decorated = True
    return func

class A:
    def foo():
        print('foo')

    @decorate
    def bar():
        print('bar')

    @classmethod
    def decorated(cls):
        def is_decorated_method(obj):
            try:
                return inspect.isfunction(obj) and obj.decorated
            except AttributeError:
                # The object has no decorated attribute
                return False

        return [result[1] for result in inspect.getmembers(cls, predicate=is_decorated_method)]

print(A.decorated())
# [<function A.bar at 0x6ffffc0aa60>]
于 2016-04-11T17:38:53.537 回答
2

Python 只是不允许你这样做。您可以使用locals(). 但是此时,您不妨将您感兴趣的变量传递给装饰器。

# using locals()

def decorator(class_namespace):
    def _decorator(func):
        class_namespace["decorated"].append(func)
        return func
    return _decorator

class A:
    store = decorator(locals())

    decorated = []

    @store
    def func(self):
        pass

    del store

一般来说,使用一对装饰器很容易。一个用来标记你感兴趣的功能,一个用来收集它们。

from types import FunctionType

def collect(cls):
    for item in vars(cls).values():
        print(item)
        if isinstance(item, FunctionType) and getattr(item, "marked", False):
            cls.marked_funcs.append(item)
    return cls

def mark(func):
    func.marked = True
    return func

@collect
class B:
    marked_funcs = []

    @mark
    def func(self):
        pass

但是在您的情况下,在类的末尾创建一组函数名称可能会更简单。例如。

class C:
    def func(self):
        pass

    func_names = [f.__name__ for f in [func]]
于 2016-04-11T18:14:02.480 回答
1
y = 20
def f():
    x = 7
    def g():
        nonlocal x # 7
        global y # 20

nonlocal限定符是指外部函数范围内的名称,不包括模块范围。而global做互补。所以你使用nonlocal不正确。

于 2016-04-11T17:06:52.620 回答
0

那个怎么样?

decorated = []

def decorator(func):
    decorated.append(func.__name__)
    def wrapper(self):
        print('wrapper called')
        func(self)
    return wrapper

class A:
    @decorator
    def f(self): print('function called')

print(decorated)
A().f()

输出:

['f']
wrapper called
function called

笔记:

您提供的遇到您所描述的问题的代码var是类变量,因此必须引用它,A.var但您不能在代码中这样做,因为您在A定义之前尝试使用它。如果它是不同的类,那将是可能的:

class X:
    decorated = []

def decorator(func):
    X.decorated.append(func.__name__)
    return func

class A:

    @decorator
    def f(self):
        pass

print(X.decorated)

请注意,nonlocal如果您不分配给变量而是调用诸如append().

于 2016-04-11T16:59:30.740 回答