python基础——自定义自动编写类的工具

class MyTools:
    @classmethod
    def makeClass(cls, className, attributes, filepath):
        """
        :param className: 类名字符串
        :param attributes: 类中的属性列表
        :param filepath: 文件路径,最好是绝对路径
        :return:
        """
        # 第一行生成class 类名:
        lines = [
            f"\nclass {className}:"
        ]
        # 第二行生成def __init__(self, 属性名, 属性名...)
        init_lines = []
        # 根据属性名生成getter、setter方法
        """
        @property
        def 属性名(self):
            return self.__属性名
        
        @属性名.setter
        def 属性名(self, 属性名):
            self.__属性名 = 属性名
        
        """
        gsetter_lines = []
        """
        生成一个__str__方法:
        def __str__(self):
            return '{属性名: 值, ...}'    
        """
        __str_lines = []
        __str_lines.append('\tdef __str__(self):')
        __str_line = '\t\treturn "{'
        line = '\tdef __init__(self, '
        format_str = ' % ('
        for index, attribute in enumerate(attributes):
            line += attribute
            # 生成self.__属性名 = 属性名
            init_line = f'\t\tself.__{attribute} = {attribute}'
            init_lines.append(init_line)
            # 生成getter、setter方法
            gsetter_lines.append('\t@property')
            gsetter_lines.append(f'\tdef {attribute}(self):')
            gsetter_lines.append(f'\t\treturn self.__{attribute}\n')
            gsetter_lines.append(f'\t@{attribute}.setter')
            gsetter_lines.append(f'\tdef {attribute}(self, {attribute}):')
            gsetter_lines.append(f'\t\tself.__{attribute} = {attribute}\n')
            __str_line += attribute + ': ' + '%s'
            format_str += 'self.__' + attribute
            if (len(attributes) - 1) != index:
                line += ', '
                __str_line += ', '
                format_str += ', '
        line += '):'
        format_str += ')'
        __str_line += '}"'
        __str_line += format_str
        __str_lines.append(__str_line)
        lines.append(line)
        lines.extend(init_lines)
        lines.extend(gsetter_lines)
        lines.extend(__str_lines)
        try:
            with open(filepath, 'w', encoding='utf-8') as file:
                for line in lines:
                    file.write(line + '\n')
                print(f'类{className}生成成功')
        except Exception as error:
            print(error)
            print('类生成失败!')


if __name__ == '__main__':
    MyTools.makeClass('student', ['a', 'b', 'c'], '')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值