# -*- encoding: utf-8 -*-
class student:
name = ''
age = 0
def __init__(self, name, age):
self.name = name
self.age = age
def convert_to_dict(obj):
'''把object物件轉換成dict物件'''
dict = {}
dict.update(obj.__dict__)
return dict
def convert_to_dicts(objs):
'''把物件列表轉換為字典列表'''
obj_arr =
for o in objs:
#把object物件轉換成dict物件
dict = {}
dict.update(o.__dict__)
return obj_arr
def class_to_dict(obj):
'''把物件(支援單個物件、list、set)轉換成字典'''
is_list = obj.__class__ == .__class__
is_set = obj.__class__ == set().__class__
if is_list or is_set:
obj_arr =
for o in obj:
#把object物件轉換成dict物件
dict = {}
dict.update(o.__dict__)
return obj_arr
else:
dict = {}
dict.update(obj.__dict__)
return dict
stu = student('zhangsan', 20)
print '-----------'
print convert_to_dict(stu)
print '-----------'
print convert_to_dicts([stu, stu])
print '-----------'
print class_to_dict(stu)
print '-----------'
print class_to_dict([stu, stu])
stua = student('zhangsan', 20)
stub = student('lisi', 10)
stu_set = set()
stu_set.add(stua)
stu_set.add(stub)
print class_to_dict(stu_set)
Python class內建函式 str
當我們定義乙個類 class field def init self,name self.name name field field liang print field main field instance at0x10c011d40 要怎麼樣才能輸出物件的實際內容呢,我們使用str函式 clas...
Python class類轉字典
有時候會需要從包裝的類裡面取出需要的資料,但有不能直接取出來 可以通過如下 把class轉換成字典 將class轉dict,以 開頭的也要 defprops with obj pr for name in dir obj value getattr obj,name ifnot name.start...
Python class 類 裝飾器
class father def init self,name self.name name print name s self.name defgetname self return father self.name class son father def getname self return...