简化数据结构的初始化过程

如果有很多类,需要做很多样式重复的_init_()函数,可以尝试以下的方法:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019-01-23 15:31
# @Author  : 
# @File    : test_init.py
# @Software: Pycharm professional


class Structure:
    _fields = []

    def __init__(self, *args):
        if len(args) != len(self._fields):
            raise TypeError('arguments not match')
        for name, value in zip(self._fields, args):
            setattr(self, name, value)


class Stock(Structure):
    _fields = ['name', 'price']


class Shose(Structure):
    _fields = ['id']


if __name__ == '__main__':
    s = Stock('AAA', 15)
    shose = Shose(1)
    print(s.name)
    print(s.price)
    print(shose.id)

posted @ 2019-01-23 15:40  xLI4n  阅读(198)  评论(0编辑  收藏  举报