python获取一个类的所有属性_获取所有可能的类属性的完整列表

^{}基本上是一个方便的方法,它不应该返回所有内容,它的基本功能是递归地返回在类及其基的字典中找到的所有内容。在def dir(*args):

...

elif isinstance(obj, (types.TypeType, types.ClassType)):

# Don't look at __class__, as metaclass methods would be confusing.

return sorted(_classdir(obj))

...

def _classdir(klass):

"""Return a set of the accessible attributes of class/type klass.

This includes all attributes of klass and all of the base classes

recursively.

"""

names = set()

ns = getattr(klass, '__dict__', None)

if ns is not None:

names.update(ns)

bases = getattr(klass, '__bases__', None)

if bases is not None:

# Note that since we are only interested in the keys, the order

# we merge classes is unimportant

for base in bases:

names.update(_classdir(base))

return names

由于每个类基本上都继承自object,因此您将看到包含一些dunder方法,因为它们实际上是object字典的一部分:

^{2}$

Now what about __bases__ and other missing items?>>> isinstance(type, object)

True

>>> isinstance(object, type)

True

>>> issubclass(type, object)

True

>>> issubclass(object, type)

False

>>> type.mro(object)

[]

>>> type.mro(type)

[, ]

因此,所有属性,如__bases__,__ge__等实际上都是type的一部分:>>> list(type.__dict__)

['__module__', '__abstractmethods__', '__getattribute__', '__weakrefoffset__', '__dict__', '__lt__', '__init__', '__setattr__', '__subclasses__', '__new__', '__base__', '__mro__', 'mro', '__dictoffset__', '__call__', '__itemsize__', '__ne__', '__instancecheck__', '__subclasscheck__', '__gt__', '__name__', '__eq__', '__basicsize__', '__bases__', '__flags__', '__doc__', '__delattr__', '__le__', '__repr__', '__hash__', '__ge__']

因此,当我们A.__bases__时,我们实际上是在查找descriptor on type of ^{},即type:>>> A.__bases__

(,)

>>> type(A).__dict__['__bases__'].__get__(A, type)

(,)

因此,由于A是{}的一个实例,这些方法不是它自己的字典的一部分,而是它的类型字典的一部分。在>> class A(object):

... spam = 'eggs'

...

>>> a = A()

>>> a.foo = 100

>>> a.bar = 200

>>> a.__dict__

{'foo': 100, 'bar': 200}

>>> A.__dict__

dict_proxy({'__dict__': , '__module__': '__main__', '__weakref__': , '__doc__': None, 'spam': 'eggs'})

由于type是object的子类,对type的dir()调用将包含来自{}的一些项:>>> set(dir(type)) - set(type.__dict__)

set(['__reduce_ex__', '__str__', '__format__', '__reduce__', '__class__', '__subclasshook__', '__sizeof__'])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值