質問

Is there a simple method for finding all of the descriptors in a class type? If I have this code:

class Descriptor(object):

    def __init__(self):
        self._name = ''

    def __get__(self, instance, owner):
        print "Getting: %s" % self._name
        return self._name

    def __set__(self, instance, name):
        print "Setting: %s" % name
        self._name = name.title()

    def __delete__(self, instance):
        print "Deleting: %s" %self._name
        del self._name

class ContrivedExample(object):
   Name = Descriptor()
   Date = Descriptor()

How do I find out that ContrivedExample.Name and ContrivedExample.Date exist from outside the class?

役に立ちましたか?

解決

You can iterate through the class' __dict__ property, which stores all of the defined names within the class, and check the type of the value for each name.

descriptors = [m for m,v in ContrivedExample.__dict__.iteritems()
               if isinstance(v, Descriptor)]

# descriptors is set to ['Name', 'Date']
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top