简体   繁体   English

在Python中,如何在描述符上调用实例方法?

[英]In Python, how can I call an instance method on a descriptor?

Given a descriptor class MyDescriptor with an extra method describe , and a class that defines an attribute a using the descriptor, how can I call the method describe on a ? 给定一个描述符类MyDescriptor一个额外的方法describe和定义一个使用描述符的属性的类,我怎么能调用的方法describea

class MyClass(object):
    a = MyDescriptor()

    def dump(self):
        print a.describe()

When I create an instance of MyClass, set its attribute a to 42 and then call dump() , I get: 当我创建MyClass的实例时,将其属性a设置为42,然后调用dump() ,我得到:

"AttributeError: 'int' object has no attribute 'describe'".

I'd like to use the descriptor to carry some metadata about the way its set method was called. 我想使用描述符来携带关于其set方法被调用方式的一些元数据。 I need to find a way to ask the descriptor instance for that metadata. 我需要找到一种方法来向描述符实例询问该元数据。

To access the descriptor object itself you need to call it using class's __dict__ attribute. 要访问描述符对象本身,您需要使用类的__dict__属性来调用它。

def dump(self):
    print type(self).__dict__['a'].describe()

For more info on descriptors read Descriptor HowTo Guide . 有关描述符的更多信息,请阅读Descriptor HowTo Guide

Demo: 演示:

class MyDescriptor(object):

    def __get__(self, obj, type=None):
        return self._val

    def __set__(self, obj, val):
        self._val = val

    def describe(self):
        return 'inside describe'

class MyClass(object):

    a = MyDescriptor()

    def __init__(self):
        self.a = 42

    def dump(self):
        print 'Inside dump()'
        print self.a.describe()

    def dump2(self):
        print 'Inside dump2()'
        print type(self).__dict__['a'].describe()

MyClass().dump2()
print '-'*20
MyClass().dump()

Output: 输出:

Inside dump2()
inside describe
--------------------
Inside dump()

Traceback (most recent call last):
  File "C:\Python27\SO.PY", line 26, in <module>
    MyClass().dump()
  File "C:\Python27\SO.PY", line 19, in dump
    print self.a.describe()
AttributeError: 'int' object has no attribute 'describe'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM