python-vars/dir

官方中英文解释:

  • vars:返回具有__dict__属性的模块、类、实例或任何其他对象的__dict__属性。Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.

  • dir:如果对象具有名为的__dir__()方法,则将调用此方法并且必须返回属性列表。如果对象未提供__dir__(),则该函数会尽力从对象的__dict__属性(如果已定义)和类型对象中收集信息。If the object has a method named __dir__(), this method will be called and must return the list of attributes. If the object does not provide __dir__(), the function tries its best to gather information from the object’s __dict__ attribute, if defined, and from its type object.

个人理解:

  • vars:返回非私有属性变量-值,不包括方法

  • dir:返回所有属性,包括方法,(如果不重写该魔法函数)

例子:


import json

class A(object):
    def __init__(self):
        self.b = 'c'
        self.a = None
    def self_method(self):
        self.m = None
    def __repr__(self):
        print('vars : ', vars(self))
        print('dir : ', dir(self))
        return str(self.__class__) + ' : ' + json.dumps(vars(self), sort_keys=True, indent=4)

obj = A()

__repr__为交互式或print时候的打印值


>>> print(obj)
vars : {'a': None, 'b': 'c'}
dir : ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'self_method']
<class '__main__.A'> : {
    "a": null, 
    "b": "c"
}

>>> print(vars(obj))
{'a': None, 'b': 'c'}

>>> print(dir(obj))

['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'self_method']

调用函数后


>>> obj.self_method()
>>> print(obj)

vars : {'a': None, 'b': 'c', 'm': None}
dir : ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'm', 'self_method']
<class '__main__.A'> : {
    "a": null, 
    "b": "c", 
    "m": null
}
>>> print(vars(obj))

{'a': None, 'b': 'c', 'm': None}
>>> print(dir(obj))

['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'm', 'self_method']

先做记录,如果之后发现理解有误,再更改。

pass

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值