python 如何列出所有类属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1215408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:43:00  来源:igfitidea点击:

How to list all class properties

pythonserializationproperties

提问by tefozi

I have class SomeClass with properties. For example idand name:

我有类 SomeClass 与属性。例如idname

class SomeClass(object):
    def __init__(self):
        self.__id = None
        self.__name = None

    def get_id(self):
        return self.__id

    def set_id(self, value):
        self.__id = value

    def get_name(self):
        return self.__name

    def set_name(self, value):
        self.__name = value

    id = property(get_id, set_id)
    name = property(get_name, set_name)

What is the easiest way to list properties? I need this for serialization.

列出属性的最简单方法是什么?我需要这个进行序列化。

回答by Mark Roddy

property_names=[p for p in dir(SomeClass) if isinstance(getattr(SomeClass,p),property)]

回答by Alex Martelli

import inspect

def isprop(v):
  return isinstance(v, property)

propnames = [name for (name, value) in inspect.getmembers(SomeClass, isprop)]

inspect.getmembersgets inherited members as well (and selects members by a predicate, here we coded ispropbecause it's not among the many predefined ones in module inspect; you could also use a lambda, of course, if you prefer).

inspect.getmembers也获取继承的成员(并通过谓词选择成员,我们在这里编码isprop是因为它不在 module 中的许多预定义成员中inspectlambda当然,如果您愿意,也可以使用 a )。