1. 程式人生 > >python對象轉字典

python對象轉字典

__init__ style att color ini 獲取 -s code 方法

詳細如下:

 1 class TestDict:
 2     name = "wyb"
 3     age = "21"
 4 
 5     def __init__(self):
 6         self.gender = male
 7 
 8     def keys(self):                         # 獲取字典的鍵
 9         s = (name, age, gender)
10         return s
11 
12     def __getitem__(self, item):            # 獲取鍵對應的值
13 return getattr(self, item) # getattr獲取對象下某個屬性的值 14 15 16 o = TestDict() 17 print(dict(o)) # 創建字典 -> 先調用對象下的keys方法再用o["xxx"]獲取值([]本質上是調用對象下的__getitem__方法)

python對象轉字典