近期在学习python,一直在和java做对比,目前没有发现有通过字段自动生成getter setter方法,故此自己写了一个类,可以通过__init__方法传入类名和字段数组,再调用内部的方法,就可以自动生成一个bean类,代码如下:
代码很简单,但还有许多可以完善的地方,比较空格符,参数是否为保留字,append方法中通过+号连接的字符串等,有强迫症的码友可以加以完善。
class ConvertBean:
def __init__(self, className, parameters):
self.__className = className
self.__parameters = parameters
def convert(self):
classStr = "class {0}:\n def __init__(self,{1}):\n{2}\n\n{3}\n{4}"
propertyStr = "@property"
setterStr = ".setter"
initParms = []
initParmsAss = []
initParmsGetter = []
initParmsSetter = []
size = len(self.__parameters)
for i in range(size):
__parm = self.__parameters[i]
initParms.append(__parm)
initParmsAss.append(" self.__" + __parm + " = " + __parm)
initParmsGetter.append(
" " + propertyStr + "\n def " + __parm + "(self):\n return self.__" + __parm + "\n")
initParmsSetter.append(
" @" + __parm + setterStr + "\n def " + __parm + "(self, " + __parm + "):\n self.__" + __parm + " = " + __parm + "\n")
__initParmsForInitParms = ",".join(initParms) # 填充构造函数参数
__initParmsForAssignment = "\n".join(initParmsAss) # 参数赋值
__initParmsForGetter = "\n".join(initParmsGetter) # 生成getter
__initParmsForSetter = "\n".join(initParmsSetter) # 生成setter
print(classStr.format(self.__className, __initParmsForInitParms, __initParmsForAssignment, __initParmsForGetter,
__initParmsForSetter))
bean = ConvertBean("Student", ["name", "age", "phone"])
bean.convert()