python - 有没有一种简洁的方法来获取 python 类中定义的所有描述?

标签 python properties descriptor

是否有一种简单的方法可以找到类类型中的所有描述符?如果我有这段代码:

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()

如何从类外部发现 ContrivedExample.Name 和 ContrivedExample.Date 存在?

最佳答案

您可以遍历类的 __dict__ 属性,该属性存储类中所有已定义的名称,并检查每个名称的值的类型。

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

# descriptors is set to ['Name', 'Date']

关于python - 有没有一种简洁的方法来获取 python 类中定义的所有描述?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15826333/

相关文章:

python - 如何在 flask 脚本的@manager.options 中设置默认值

c# - 属性(property)决定论

python - 使用 Python 描述符 : How best to write a general validation getter-setter

python - 如何为 Python 属性实现 __iadd__

python - "class"与 "instance of class"__get__ 和 __set__?

python - python中的Language_check继承错误

python - 在 python 中将列表分解为重叠的元组列表

Python Pip 安装失败 - 无法构建 Egg。由于 google cloud sql 也无法使用 1.2.5

c# - 不确定何时使用抽象属性,何时不使用

c# - 使用 LINQ 时从字符串访问 lambda 表达式中的属性