我一直在尝试使用与装饰器一起使用的__get__
__set__
和__delete__
魔术方法将类的方法(而不是实例)放到装饰器上。除了__get__
之外,我完全无法工作/被打电话。我已经尝试过代码的每种组合/排列,但是最近的样子是这样的:
def my_decorator5(func: Callable[..., R]) -> R:
""" Decorate func while preserving the signature. """
print(f"{'*'*40} my_decorator main")
class Wrap(object):
def __init__(self, clsmethod) -> None:
print(f"{'*'*40} is __init__")
self.value = None
self.func = func
self.clsmethod = clsmethod
self.func_name = func.__name__
def __get__(self, obj, cls) -> R:
print(f"{'*'*40} {cls} is getting")
owner = cls
self.value = func(cls)
return cast(R, self.value)
def __set__(self, cls, newval) -> None:
print(f"{'*'*40} {cls} is setting")
self.value = newval
def __set_name__(self, cls, newval) -> None:
print(f"{'*'*40} {self} is __set_name__")
print(f"{'*'*40} {cls} is __set_name__")
print(f"{'*'*40} {newval} is __set_name__")
def __delete__(self, cls) -> None:
print(f"{'*'*40} {cls} is deleting")
delattr(self, "value")
def __delattr__(self, key) -> None:
print(f"{'*'*40} {self} is __delattr__")
我有测试代码:
class foo3:
@my_decorator5
def foo3_str(self) -> str:
return "Original foo3 str"
print(f"\n{'*'*80}\n{'*'*35} STARTING {'*'*35}\n{'*'*80}\n")
print(f"\n--{dir(foo3.foo3_str)}--\n")
print(f"\n--{foo3.foo3_str.__class__}--\n")
print(f"\n--{dir(foo3.__dict__['foo3_str'])}--\n")
print(f"\n--\tatrr: {foo3.foo3_str.__class__}\n\t__dict__{foo3.__dict__['foo3_str'].__class__}\n\t{foo3.__dict__['foo3_str'].__set__(1,2)}--\n")
print(">>>> getting >>>>")
print(f"foo3_str ==> {foo3.foo3_str}")
print(f"<<<< got foo3_str <<<<")
print("\n")
print(f"\n--\tatrr: {foo3.foo3_str.__class__}\n\t__dict__{foo3.__dict__['foo3_str'].__class__}--\n")
print(">>>> settting >>>>")
foo3.foo3_str = "Set foo3 str"
print("<<<< set foo3_str <<<<")
print(f"\n--\tatrr: {foo3.foo3_str.__class__}\n\t__dict__{foo3.__dict__['foo3_str'].__class__}--\n")
print("\n")
print(f"foo3_str ==> {foo3.foo3_str}")
print("\n")
print(f">>>> deleting foo3_str")
del foo3.foo3_str
print(f"<<<< deleted foo3_str <<<<")
print("\n")
print(">>>> getting")
try:
print(f"foo3_str ==> {foo3.foo3_str}")
foo3.foo3_str = "Eric"
except AttributeError:
print("...foo3.foo3_str AttributeError")
print(" <<<< getting foo3_str")
我的输出是:
**************************************** my_decorator main
**************************************** is __init__
**************************************** <__main__.my_decorator5.<locals>.Wrap object at 0x000002D185BA6470> is __set_name__
**************************************** <class '__main__.foo3'> is __set_name__
**************************************** foo3_str is __set_name__
********************************************************************************
*********************************** STARTING ***********************************
********************************************************************************
**************************************** <class '__main__.foo3'> is getting
--['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']--
**************************************** <class '__main__.foo3'> is getting
--<class 'str'>--
--['__class__', '__delattr__', '__delete__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__set__', '__set_name__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'clsmethod', 'func', 'func_name', 'value']--
**************************************** <class '__main__.foo3'> is getting
**************************************** 1 is setting
-- atrr: <class 'str'>
__dict__<class '__main__.my_decorator5.<locals>.Wrap'>
None--
>>>> getting >>>>
**************************************** <class '__main__.foo3'> is getting
foo3_str ==> Original foo3 str
<<<< got foo3_str <<<<
**************************************** <class '__main__.foo3'> is getting
-- atrr: <class 'str'>
__dict__<class '__main__.my_decorator5.<locals>.Wrap'>--
>>>> settting >>>>
<<<< set foo3_str <<<<
-- atrr: <class 'str'>
__dict__<class 'str'>--
foo3_str ==> Set foo3 str
>>>> deleting foo3_str
<<<< deleted foo3_str <<<<
>>>> getting
...foo3.foo3_str AttributeError
>> getting foo3_str
**************************************** my_decorator main
当行
foo3.foo3_str = "Set foo3 str"
我本来希望看到的
**************************************** ... is setting
但是__set__
函数将被完全忽略,而类的 dict 被设置为实际的str
类型。
是否有可能在类属性的装饰器上进行get,set,delete或没有实例将仅运行__get__
而不运行__set__
和__detele__
?
答案 0 :(得分:2)
仅当您在实例中分配描述符的名称时,才调用描述符的0
方法。如果直接分配给该类,则将覆盖描述符(不调用__set__
)。相反,__set__
方法被调用以在类或实例上进行查找。某些描述符(例如__get__
)被编程为在类上调用时返回自身,因此,它们的property
方法实际上并未运行可能并不明显。
如果要使用描述符来控制对类变量的访问,则需要将描述符放入元类(类对象的类)中。这是一个基本示例,使用__get__
控制名为property
的类变量:
foo