如何在class
定义体内循环已初始化的属性?
假设一个班级:
class WakeUp:
def __init__(self,date,time):
self.date = str(date)
self.time = str(time)
self.brush_teeth = brushteeth
.
.
def get_wakeup_activities(self):
return 'date: ' + self.date + 'time' + self.time. + 'brush_teeth', + self.brush_teeth
我打算避免详细输入,希望将方法重构为:
def get_wakeup_activities(self):
act_list = ()
for attr in attrs:
act_list.append(attr)
return 'date: %s time:%s brush_teeth: %s' %tuple(act_list)
调用方法时,输出
date:2017-10-17 time:11:50:27 ...
或更抽象:
def get_wakeup_activities(self):
wakeup_dict = {k:v for k, v in self.attrs}
return wakeup_dict
打电话的命令:
today_wakeup = Wakeup
today_wakeup.get_wakeup_activities()
输出:
{date:2017-10-17, time:11:50:27,....}
答案 0 :(得分:1)
class WakeUp:
def __init__(self,date,time, brushteeth):
self.date = str(date)
self.time = str(time)
self.brush_teeth = brushteeth
def get_wakeup_activities(self):
return self.__dict__
today_wakeup = WakeUp('today', '8am', 'YES!')
print(today_wakeup.get_wakeup_activities())