0

我有一个实例属性,我使用 Python 的property装饰器创建了一个属性。

然后,我使用 decorator 为该属性创建了一个设置器@property_name.setter

我怎样才能得到__qualname__原始方法定义的,用 装饰@property.setter


我看过的地方


示例代码

这是写在Python 3.6.

#!/usr/bin/env python3


def print_qualname():
    """Wraps a method, printing its qualified name."""

    def print_qualname_decorator(func):
        # print(f"func = {func} and dir(): {dir(func)}")
        if hasattr(func, "__qualname__"):
            print(f"Qualified name = {func.__qualname__}.")
        else:
            print("Doesn't have qualified name.")

    return print_qualname_decorator


class SomeClass:

    def __init__(self):
        self._some_attr = 0
        self._another_attr = 0

    @property
    def some_attr(self) -> int:
        return self._some_attr

    @print_qualname()
    @some_attr.setter
    def some_attr(self, val: int) -> None:
        self._some_attr = val

    @print_qualname()
    def get_another_attr(self) -> int:
        return self._another_attr

输出:

Doesn't have qualified name.
Qualified name = SomeClass.get_another_attr.

如何从装饰器内部获取__qualname__for ?换句话说,我如何才能被输出?some_attrprint_qualnameSomeClass.some_attr

4

1 回答 1

1

您可以为 setter 翻转装饰器的顺序。注意我已经调整了print_qualname_decorator调用底层函数并返回它(否则setter将不会执行)。

from functools import wraps

def print_qualname(func):
    """Wraps a method, printing its qualified name."""
    @wraps(func)
    def print_qualname_decorator(*args):
        if hasattr(func, "__qualname__"):
            print(f"Qualified name = {func.__qualname__}.")
        else:
            print("Doesn't have qualified name.")
        return func(*args)
    return print_qualname_decorator


class SomeClass:

    def __init__(self):
        self._some_attr = 0
        self._another_attr = 0

    @property
    def some_attr(self) -> int:
        return self._some_attr

    @some_attr.setter
    @print_qualname
    def some_attr(self, val: int) -> None:
        self._some_attr = val

    @print_qualname
    def get_another_attr(self) -> int:
        return self._another_attr

利用

In [46]: foo = SomeClass()                                               

In [47]: foo.get_another_attr()                                          
Qualified name = SomeClass.get_another_attr.
Out[47]: 0

In [48]: foo.some_attr = 5                                               
Qualified name = SomeClass.some_attr.

In [49]: foo._some_attr                                                  
Out[49]: 5
于 2019-12-17T06:06:43.953 回答