简体   繁体   English

如何获取除魔术方法/属性之外的已定义类属性的dict?

[英]How to get dict of defined class attributes exclusive of magic methods/attributes?

Basically, what I am doing is 基本上我在做什么

class A(object):
    a = 1
    b = 2

copy.deepcopy(dict(A.__dict__))

It gives the error 它给出了错误

TypeError: object. TypeError:对象。 new (getset_descriptor) is not safe, use getset_descriptor. new (getset_descriptor)不安全,请使用getset_descriptor。 new () ()

If I update code like below one and pop out __dict__ and __weakref __ from class dictionary items 如果我更新下面的代码,并从类字典项中弹出__dict____weakref __

class A(object):
    a = 1
    b = 2

attrs = dict(A.__dict__)
attrs.pop("__weakref__")
attrs.pop("__dict__")
copy.deepcopy(dict(A.__dict__))
# It gives {'__module__': '__main__', 'a': 1, 'b': 2, '__doc__': None}

It works fine, I understand this is something related to copying weakref which will be wrong. 它工作正常,我知道这与复制weakref有关,这是错误的。

Is there any better way of doing the same where I don't need to specifically pop out __dict__ and __weakref __ and I can get only attributes of the Class, exclusive of magic methods/attributes? 有没有更好的方法做同样的事情,我不需要专门弹出__dict____weakref __而我只能得到类的属性 ,不包括魔法方法/属性?

It's not really that simple in Python, since there often isn't any way to know what's "built-in" and what's not. 它在Python中并不是那么简单,因为通常没有任何方法可以知道什么是“内置”,什么不是。 Also, using __dict__ isn't sufficient if you want to get inherited attributes; 另外,如果你想获得继承属性,使用__dict__是不够的; for that, you'd need to use dir instead, which conveniently also handles instances of objects the same as it'd handle classes themselves, and is thus more general purpose. 为此,您需要使用dir代替,它可以方便地处理对象实例,就像处理类本身一样,因此更通用。

The simplest general-purpose solution would be to define yourself a simple little function that encapsulates what you want in terms of "attributes". 最简单的通用解决方案是定义一个简单的小函数,根据“属性”封装你想要的东西。 You can then explicitly remove attributes you don't want to keep around (though, notice that if you deep copy such a filtered object, you probably won't have a usable Python object anymore): 然后,您可以显式删除您不想保留的属性(不过,请注意,如果您深度复制了此类过滤对象,则可能不再有可用的Python对象):

In [1]: {k: getattr(A, k) for k in set(dir(A)) - set(dir(object)) - {'__weakref__', '__dict__', '__module__'}}
Out[1]: {'b': 2, 'a': 1}

In [2]: class B(A):
    ...:     c = 10

In [3]: {k: getattr(B, k) for k in set(dir(B)) - set(dir(object)) - {'__weakref__', '__dict__', '__module__'}}
Out[3]: {'b': 2, 'c': 10, 'a': 1}

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

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