Python 如何获得用 property.setter 包装的方法的 __qualname__

Python how to get __qualname__ of method wrapped with property.setter

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

然后我使用装饰器 @property_name.setter.

为 属性 做了一个 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.

如何从 print_qualname 装饰器中获取 some_attr__qualname__?换句话说,如何让 SomeClass.some_attr 输出?

您可以翻转 setter 装饰器的顺序。请注意,我已经调整了 print_qualname_decorator 以调用底层函数并 return 它(否则 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