我试图模仿带有装饰函数的描述符,但失败了。这是我尝试过的。
def my_property(self):
def wrapper(func):
return func(self)
return wrapper
class C:
def __init__(self):
self._x = 0
@my_property(C()) # this will print 0 for me, but it's not from the obj `c`
def p(self):
return self._x
c = C()
print(c.p)直接在装饰器中重写__get__也没有帮助我。我还试图继承function类并重写它的__get__方法,但是被告知function是最终的,而不是子类(也许我应该尝试forbiddenfruit https://github.com/clarete/forbiddenfruit)。
有人能帮忙吗?
编辑:为了澄清,我想知道是否可以不使用关键字class
发布于 2022-02-10 02:59:10
你的直觉推翻__get__是正确的。事实上,Python中的属性正是这样工作的。
考虑一下
class MyProperty:
def __init__(self, func):
self.func = func
def __get__(self, instance, owner):
return self.func(instance)MyProperty是一个实例包含func的类。当我们从类中__get__一个MyProperty实例时,它将自动调用内部函数。
现在,我们将为它创建一个整洁的包装函数。非常琐碎,但与Python对函数和类型的命名保持一致还是很好的
def my_property(func):
return MyProperty(func)最后,使用装饰师。
class C:
def __init__(self):
self._x = 0
@my_property
def p(self):
return self._x
c = C()
print(c.p) # Prints 0https://stackoverflow.com/questions/71059221
复制相似问题