Are unbound descriptors possible?

試著忘記壹切 提交于 2019-12-21 23:34:39

问题


(and if not, is there an approach that accomplishes a similar thing?)

For example, here's an example of a "bound" descriptor:

class VerboseDescriptor(object):
    def __init__(self, init):
        self.val = init

    def __get__(self, obj, typ=None):
        print("[%s] Get is %s" % (obj, self.val))
        return self.val

    def __set__(self, obj, val):
        print("[%s] Set to %s" % (obj, val))
        self.val = val


class Holder(object):
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return "Holder(%s)" % self.name

    val = VerboseDescriptor(2)


foo = Holder("foo")
_ = foo.val
foo.val = 4

Output (as expected):

[Holder(foo)] Get is 2
[Holder(foo)] Set to 4

Of course, something similar could be done with properties.

But, in the example, the VerboseDescriptor instance has to be an attribute of a class or instance (in this case, the class Holder).

In other words, the following doesn't work:

class VerboseDescriptor(object):
    def __init__(self, init):
        self.val = init

    def __get__(self, obj, typ=None):
        print("[%s] Get is %s" % (obj, self.val))
        return self.val

    def __set__(self, obj, val):
        print("[%s] Set to %s" % (obj, val))
        self.val = val


val = VerboseDescriptor(2)

_ = val
val = 4

Neither __get__ or __set__ methods are called. In the first line, _ is just set to reference the same VerboseDescriptor instance as val and in the second, val is changed to reference 4.

So my question is, is there a way to build an object so that you can "catch" assignment to/from it, in the same way that descriptors allow you to catch assignment to/from class/instance attributes?

The question is more theoretical than practical. I know there are very similar methods that involve classes (similar to my Holder class) that would suffice. I'm just wondering whether this functionality is possible without Holder-type classes.

Reading:

  • Descriptor HowTo Guide
  • Implementing / Invoking Descriptors

来源:https://stackoverflow.com/questions/29322237/are-unbound-descriptors-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!