简体   繁体   English

是否有Python方法可以访问类的所有非私有和非内置属性?

[英]Is there a Python method to access all non-private and non-builtin attributes of a class?

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 (ie those that do not begin with a single or double underscore) on a class. 我想调用一种方法给我一个所有“非私有”的词典(我在这里使用“私有”一词,因为它在Python中并不存在)和非内置属性(即那些在类上不要以单个或双下划线开头。 Something like vars(MyClass) that would return only the "public" attributes on that class. 像vars(MyClass)这样的东西只能返回该类的“公共”属性。

I'm aware that 我知道

from M import * 

does not import objects whose name starts with an underscore. 不会导入名称以下划线开头的对象。 ( http://www.python.org/dev/peps/pep-0008/#id25 ) How does import implement that? http://www.python.org/dev/peps/pep-0008/#id25 )导入如何实现? Via a builtin function or just by checking for underscores? 通过内置函数或仅通过检查下划线? What is the pythonic way to do this? 什么是pythonic方法呢?

Example: 例:

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'

If I do 如果我做

vars(MyClass).keys()

I get 我明白了

['_MyClass__gets_name_mangled', '__module__', '_private', '__doc__', '__dict__', '__weakref__', 'public', '__init__']

How can I get only 我怎么才能得到

['public']

Or do I just need to check for underscores myself? 或者我只是需要自己检查下划线? It just seems like there would be a pythonic way to do this. 看起来似乎会有一种pythonic方式来做到这一点。

For more on underscores and double underscores, see: What is the meaning of a single- and a double-underscore before an object name? 有关下划线和双下划线的更多信息,请参阅: 对象名称之前的单下划线和双下划线的含义是什么?

Actually, it would be unpythonic for such function to exists - because "officially" there is no private or protected fields/properties in Python. 实际上,存在这样的函数将是unpythonic - 因为“正式”Python中没有私有或受保护的字段/属性。

While it makes sense to throw away module attributes with leading underscores (which are usually some implementation details) during import * from some module*, it is not useful in context of any other object. 虽然在从某个模块* import *期间丢弃具有前导下划线(通常是一些实现细节)的模块属性是有意义的,但它在任何其他对象的上下文中都没有用。

So, if you need to list only "public" methods/attributes of an object, just iterate through result of dir and drop names with leading underscores. 因此,如果您只需要列出对象的“公共”方法/属性,只需遍历dir结果并删除带有前导下划线的名称。


* "during import * from some module'" *“在import *期间import *从某些模块'”

Usually it is not the best practice. 通常这不是最好的做法。 Consider the next example: 考虑下一个例子:

module A has a1 and a2 defined 模块A定义了a1a2

module B has b1 and b2 defined 模块B定义了b1b2

This code in module C works as expected: 模块C此代码按预期工作:

from A import a1, a2
from B import *

Imagine we add function a1 in module B . 想象一下,我们在模块B添加了函数a1 Now suddenly module C is broken, although we haven't touched it. 现在突然模块C坏了,虽然我们还没碰过它。

With a dict comprehension that filters vars() 使用dict理解过滤vars()

{ k:v for k,v in vars(myObject).items() if not k.startswith('_') }

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

I'm using this function: 我正在使用这个功能:

def print_all_public_fields(obj):
    print(obj)
    for a in dir(obj):
        if not a.startswith('_') and not a.isupper():
            print('\t%s = %s' % (a, getattr(obj, a)))

I know it's not exactly what you want, but maybe it'll give you some idea. 我知道这不是你想要的,但也许它会给你一些想法。

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

相关问题 如何将PyObject_IsInstance与非内置类一起用作第二个参数? - How can I use PyObject_IsInstance with a non-builtin class as second argument? VScode 找不到非内置模块的定义 - VScode cant find Definitions of non-builtin modules 访问 python 中继承的 class 中的私有属性 - Access the private attributes in a inherited class in python 从 class 方法访问 python 中的 class 属性 - Access class attributes in python from class method python 中的错误“TypeError: unsupported operand type(s) for -: 'builtin_function_or_method' and 'int'” 对于非关键字变量名? - Error in python “ TypeError: unsupported operand type(s) for -: 'builtin_function_or_method' and 'int' ” for non-keyword varname? 定义非类私有函数是否意味着Python中的任何内容? - Does defining a non-class private function means anything in Python? 对非类属性使用 Python 的 __get__ 描述符 - Using Python's __get__ descriptor for non-class attributes 使用 asyncio 执行的非阻塞 python class 方法 - Non blocking python class method executed with asyncio Python遍历基类中的非继承属性 - Python loop over non-inherited attributes in base class python动态设置非实例类属性 - python dynamically set non-instance class attributes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM