【Python】类对象⾃动⽣成get,set⽅法代码
class Student:
def__init__(self):
self.name =None
self.age =None
if __name__ =='__main__':
student = Student()
print(student.__dict__)
object tofor k in student.__dict__:
print("def set_"+ k +"(self,"+ k +"):")
print("\tself."+ k,"="+ k)
print("def get_"+ k +"(self):")
print("\treturn self."+ k)
输出结果:
{'name':None,'age':None}
def set_name(self,name):
self.name =name
def get_name(self):
return self.name
def set_age(self,age):
self.age =age
def get_age(self):
return self.age
将get,set⽅法赋值粘贴到类⽅法
将字典转化为对象
def dict_to_obj(dictObject: dict, obj):
for k,v in dictObject.items():
obj.__dict__[k] = v
return obj
if __name__ == '__main__':
d = {"id":"123", "name":"class", "age":"18"}
stu: Student = dict_to_obj(d, Student())
print(stu.id)
print(stu.age)
print(stu.name)
_id())
_name())
_age())
⼯具类
def dict_to_str(dict_object: dict, ensure_ascii=False):
return json.dumps(dict_object, ensure_ascii=ensure_ascii)
def str_to_dict(str_object: str):
dic = json.loads(str_object)
return dic
def object_to_json_string(self, ensure_ascii=False):
return json.dumps(self, default=lambda o: o.__dict__, ensure_ascii=ensure_ascii)
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论