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

mac2022-06-30  107

如果有很多类,需要做很多样式重复的_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)

转载于:https://www.cnblogs.com/xLI4n/p/10309343.html

最新回复(0)