[英]Python how to get __qualname__ of method wrapped with property.setter
I have an instance attribute that I made a property using Python's property
decorator.我有一个实例属性,我使用 Python 的
property
装饰器创建了一个属性。
I then made a setter for the property using the decorator @property_name.setter
.然后我使用装饰器
@property_name.setter
为属性创建了一个 setter。
How can I get the __qualname__
of the original method definition, decorated with @property.setter
?如何获得用
@property.setter
修饰的原始方法定义的__qualname__
?
Where I Have Looked我看过的地方
property
uses @functools.wraps()
property
使用@functools.wraps()
property
is actually a descriptor
property
实际上是一个descriptor
__get__
, but I can't figure out the syntax__get__
,但我无法弄清楚语法Example Code示例代码
This was written in Python 3.6
.这是用
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
Output:输出:
Doesn't have qualified name.
Qualified name = SomeClass.get_another_attr.
How can I get the __qualname__
for some_attr
from inside the print_qualname
decorator?我怎样才能获得
__qualname__
为some_attr
从里面print_qualname
装饰? In other words, how do I get SomeClass.some_attr
to be output?换句话说,如何让
SomeClass.some_attr
输出?
You could flip the ordering of the decorators for the setter.您可以翻转 setter 装饰器的顺序。 Note I've adjusted the
print_qualname_decorator
to call the underlying function and return it (otherwise the setter will not execute).注意我已经调整了
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
Use用
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.