是否存在Python方法来访问类的所有非私有和非内建属性? [英] Is there a Python method to access all non-private and non-builtin attributes of a class?
问题描述
我想调用一个方法来给我所有非私有"(由于在Python中它实际上并不存在,我在这里使用了私有"一词,因为它实际上并不存在)的字典.也就是说,那些不是以单下划线或双下划线开头的类).像vars(MyClass)这样的东西只会返回该类的公共"属性.
I would like to call a method to give me a dict of all of the "non-private" (I use the term "private" somewhat loosely here since it does not really exist in Python) and non-builtin attributes (i.e. those that do not begin with a single or double underscore) on a class. Something like vars(MyClass) that would return only the "public" attributes on that class.
我知道
from M import *
不会导入名称以下划线开头的对象.( http://www.python.org/dev/peps/pep-0008/#id25 )导入如何实现?通过内置函数还是仅检查下划线?pythonic的方法是什么?
does not import objects whose name starts with an underscore. (http://www.python.org/dev/peps/pep-0008/#id25) How does import implement that? Via a builtin function or just by checking for underscores? What is the pythonic way to do this?
示例:
class MyClass(object):
def __init__(self):
do_stuff()
def _private(self):
print 'private'
def __gets_name_mangled(self:
print 'becomes _MyClass__gets_name_mangled()'
def public(self):
print 'public'
如果我这样做
vars(MyClass).keys()
我知道
['_MyClass__gets_name_mangled', '__module__', '_private', '__doc__', '__dict__', '__weakref__', 'public', '__init__']
我怎么只能得到
['public']
还是我自己需要检查下划线?似乎会有一种pythonic的方式来做到这一点.
Or do I just need to check for underscores myself? It just seems like there would be a pythonic way to do this.
有关下划线和双下划线的更多信息,请参见:
For more on underscores and double underscores, see: What is the meaning of a single- and a double-underscore before an object name?
推荐答案
具有可过滤vars()的dict理解
With a dict comprehension that filters vars()
{ k:v for k,v in vars(myObject).items() if not k.startswith('_') }
移动到一个函数中,该函数返回非软件专用"或可调用属性的列表.您可以根据需要通过更改上述的dict理解来返回值
Moved into a function that returns a list of attributes that are not 'soft private' or callables. You can return values if you like by changing to dict comprehension as above
def list_public_attributes(input_var):
return [k for k, v in vars(input_var).items() if
not (k.startswith('_') or callable(v))]
这篇关于是否存在Python方法来访问类的所有非私有和非内建属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!