Python __dict__ differs from DIR ()

Source: Internet
Author: User
Tags print object


Python __dict__ with Dir ()




    • Python __dict__ and Dir
      • __dict__ Property
      • Dir function
      • Conclusion





Reprint please indicate the source (http://blog.csdn.net/lis_12/article/details/53521554).



Python has all the objects, each object has multiple properties (attribute), and Python has a unified management scheme for attributes.



__dict__与dir()The difference:


    1. Dir () is a function that returns a list;
    2. __dict__is a dictionary, the key is the property name, the value is the property value;
    3. Dir () is used to find all properties of an object, including the__dict__attributes in, which__dict__is a subset of Dir ();


 Not all objects have__dict__properties. Many of the built-in types have no__dict__attributes, such as list, and you need to use DIR () to list all the properties of the object.


__dict__Property


__dict__is a dictionary used to store object properties whose key is the property name and the value of the property.


#!/usr/bin/python
# -*- coding: utf-8 -*-
Class A(object):
    Class_var = 1
    Def __init__(self):
        Self.name = ‘xy‘
        Self.age = 2

    @property
    Def num(self):
        Return self.age + 10

    Def fun(self):pass
    Def static_f():pass
    Def class_f(cls):pass

If __name__ == ‘__main__‘: #main program
    a = A()
    Print a.__dict__ #{‘age‘: 2, _name_: attribute in the ‘xy’} instance
    Print A.__dict__
    ‘‘‘
    Class A's __dict__ attribute
    {
    ‘__dict__‘: <attribute ‘__dict__‘ of ‘A‘objects,, ## If you want to go deeper, check out the reference link 5
    ‘__module__‘: ‘__main__’, #In one module
    ‘num‘: <property object>, #attribute object
    ‘class_f‘: <function class_f>, #class method
    ‘static_f‘: <function static_f>, #static method
    ‘class_var’: 1, ‘fun‘: <function fun >, #类variable
    ‘__weakref__‘: <attribute ‘__weakref__‘ of ‘A’ objects>,
    ‘__doc__‘: None, #class description string
    ‘__init__‘: <function __init__ at 0x0000000003451AC8>}
    ‘‘‘

    A.level1 = 3
    A.fun = lambda :x
    Print a.__dict__ #{‘level1‘: 3, ‘age’: 2, ‘name’: ‘xy‘, ‘fun’: <function <lambda> at 0x>}
    Print A.__dict__ # is the same as above

    A.level2 = 4
    Print a.__dict__ #{‘level1‘: 3, ‘age’: 2, ‘name’: ‘xy’}
    Print A.__dict__ #Added level2 attribute

    Print object.__dict__
    ‘‘‘
    {‘__setattr__‘: <slot wrapper ‘__setattr__‘ of ‘object’ objects>,
    ‘__reduce_ex__‘: <method ‘__reduce_ex__‘ of ‘object’ objects>,
    ‘__new__‘: <built-in method __new__ of type object at>,
    Wait.....
    ‘‘‘ 





From the above code,


    1. Instance__dict__stores only the instance properties associated with the instance,

      Because of the properties of the instance__dict__, the instance properties of each instance do not affect each other.

    2. A class__dict__stores all instances of shared variables and functions (class properties, methods, and so on), and the class__dict__does not contain properties of its parent class.




Dir () function


 Dir () is an API function provided by Python, and the Dir () function automatically looks for all properties of an object, including attributes inherited from the parent class.



? The__dict__property of an instance is simply a collection of instance properties for that instance, and does not contain all valid properties for that instance. So if you want to get all the valid properties of an object, you should use Dir ().


Print dir(A)
‘‘‘
[ '__Class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', ' __repr__ ',' __setattr__ ',' __sizeof__ ',' __str__ ',' __subclasshook__ ',' __weakref__ ',' age ',' class_f ',' class_var ',' fun ',' level1 ',' level2 ',' name ' , 'num', 'static_f']
‘‘‘
A_dict = a.__dict__.keys()
A_dict = A.__dict__.keys()
Object_dict = object.__dict__.keys()
Print a_dict
Print A_dict
Print object_dict
‘‘‘
[‘fun‘, ‘level1’, ‘age’, ‘name’]

[ '__Module__', 'level2', 'num', 'static_f', '__dict__', '__weakref__', '__init__', 'class_f', 'class_var', 'fun', '__doc__']

[ '__Setattr__', '__reduce_ex__', '__new__', '__reduce__', '__str__', '__format__', '__getattribute__', '__class__', '__delattr__', '__subclasshook__', '__repr__', '__hash__', ' __sizeof__', '__doc__', '__init__']
‘‘‘

# Because each class has a __doc__ attribute, so you need to go to the weight, then go to the weight and then compare
Print set(dir(a)) == set(a_dict + A_dict + object_dict) #True 




Conclusion


The Dir () function automatically looks for all properties of an object, including__dict__the properties in.



__dict__is a subset of Dir (), and Dir () contains__dict__the attributes in.



Reference URL


    1. Https://docs.python.org/2/howto/descriptor.html?highlight=descriptor%20protocol#id1
    2. Http://stackoverflow.com/questions/4877290/what-is-the-dict-dict-attribute-of-a-python-class
    3. Http://www.tuicool.com/articles/ZbQFF3u
    4. Http://www.jb51.net/article/54540.htm
    5. http://blog.csdn.net/lis_12/article/details/53519060


Python __dict__ differs from DIR ()


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.