简体   繁体   English

如何列出所有类属性

[英]How to list all class properties

I have class SomeClass with properties. 我有类SomeClass属性。 For example id and name : 例如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. 我需要这个序列化。

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

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

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

inspect.getmembers gets inherited members as well (and selects members by a predicate, here we coded isprop because 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因为它不在模块inspect中的许多预定义的中;当然,如果您愿意,也可以使用lambda )。

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

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