python类中没有属性_如何找到Python对象的隐藏属性? (未出现在dir(obj)列表中的属性)...

dir()不会尝试提供完整的输出,只是在交互式解释器中有用的合理近似值.

dir在输出中不包含__mro__和mro的原因可以在源代码中找到,在Objects/object.c at line 1812下:

/* Helper for PyObject_Dir of type objects: returns __dict__ and __bases__.

We deliberately don't suck up its __class__,as methods belonging to the

metaclass would probably be more confusing than helpful.

*/

static PyObject *

_specialized_dir_type(PyObject *obj)

事实证明,mro方法和__mro__属性实际上是元类的属性,即类型:

>>> '__mro__' in object.__dict__

False

>>> '__mro__' in type.__dict__

True

>>> 'mro' in object.__dict__

False

>>> 'mro' in type.__dict__

True

因此它们没有显示在dir的输出中.这是否合理取决于.我相信大多数时候你真的不想看到元类定义的内容,因为它们是元类的内部结构.

如dir()的文档中所述,您可以自定义其输出,定义__dir__方法.但是这适用于类的实例:

class A(object):

def __dir__(self):

return ['a','b','c']

print(dir(A()),dir(A))

输出:

(['a','c'],['__class__','__delattr__','__dict__','__dir__','__doc__','__format__','__getattribute__','__hash__','__init__','__module__','__new__','__reduce__','__reduce_ex__','__repr__','__setattr__','__sizeof__','__str__','__subclasshook__','__weakref__'])

如果您还要自定义dir(A)的输出,则必须使用自定义元类:

class MyMeta(type):

def __dir__(self):

return ['a','c']

class A(object,metaclass=MyMeta):

# __metaclass__ = MyMeta # in python 2

def __dir__(self):

return ['a','c','d']

print(dir(A()),'d'],['a','c'])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值