Common special method or property in Python - dir dict methods and properties

A, __ dir__ method

Effect __dir __ () method of the object inside the object is to list all method names and attribute names, the method comprising the sequence will return all the properties or method name.

If the program execution dir (obj) function on an object, the object is actually the __dir __ () method returns the values ​​are sorted, and then packaged into a list.

Chestnuts as follows:

 

. 1  # Coding. 8 = UTF- 
2  class Item ():
 . 3      DEF  the __init__ (Self, name,. Price):
 . 4          the self.name = name
 . 5          self.price = . Price
 . 6      DEF info ():
 . 7          Pass 
. 8  # create an Item object , assign it to it variable 
. 9 it = Item ( ' mouse ' , 29.8 )
 10  # prints all attributes (including methods) consisting of a list 
. 11  Print (it. __DIR__ ())
 12 is  # print all attributes (including methods) consisting of list, sorted 
13  Print (dir (IT))

 

Print Console as follows:

Explanation: The program can be seen not only export our definition name, price, info three properties and methods, but also a large number of systems built-in properties and methods, such as the former two said to __repr__ and __del__ method.

 

Two, __ dict__ property

Dictionary __dict__ property is used to view objects stored inside all the attribute names and values ​​of the composition, the usual procedure directly to the property. __Dict__ can use the program to view the properties of all the internal state of an object can also be used to access or modify the value of the specified property by the dictionary syntax.

Chestnuts as follows:

 

. 1  # Coding. 8 = UTF- 
2  class Item ():
 . 3      DEF  the __init__ (Self, name,. Price):
 . 4          the self.name = name
 . 5          self.price = . Price
 . 6      DEF info ():
 . 7          Pass 
. 8  # create an Item object , it will be assigned to the variable 
. 9 it = Item ( ' mouse ' , 29.8 )
 10  Print (it. the __dict__ )
 . 11  Print (it. the __dict__ [ ' name ' ])
 12 is  Print(it.__dict__['price'])
13 it.__dict__['name'] = '键盘'
14 it.__dict__['price'] = 39.9
15 print(it.name)
16 print(it.price)

 

Print Console as follows:

Explain: __dict__ property code on line 10 is directly output target, so that the output will direct all of the attribute names and values ​​dict objects stored inside the object; The next two lines of the separate printed two attribute values; of 13, 14 line two by name and price of the property assignment __dict__ properties, and then print again appeared the new property value.

 

Guess you like

Origin www.cnblogs.com/tizer/p/11200596.html