Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีสร้าง Python Dictionary จาก Fields ของ Object

Attribute __dict__ คืนค่า Dictionary จาก Fields ของ Object ใดๆ

ลองกำหนดคลาส Person

>>> class Person:
...     def __init__(self):
...         self.name = 'foo'
...         self.age = 20
...     def show(self):
...         print(self.name, self.age)

เราประกาศ Object ของคลาสนี้และ取得 Attribute __dict__ ซึ่งเป็น Dictionary Object

>>> p = Person()
>>> d = p.__dict__
>>> d
{'name': 'foo', 'age': 20}