美文网首页
python类与对象详解(3):简化初始化过程

python类与对象详解(3):简化初始化过程

作者: KillerManA | 来源:发表于2016-04-21 08:34 被阅读654次

有时候我们编写了很多类,并且已经将这些类当作数据结构来用,但是我们需要重复编写大量重复且样式统一的init()函数,这时候我们可以将初始化过程集中到一个单独的init()函数中,并将其定义在一个公共的基类中。
代码演示:

class Structure:
    _fields = []
    def __init__(self, *args):
        if len(args) != len(self._fields):
            raise TypeError('Expected {} arguments'.format(len(self._fields)))
        for name, value in zip(self._fields, args):
            setattr(self, name, value)

if __name__ == "__main__":
    class Stock(Structure):
        _fields = ["name", "price", "shares"]

这样我们实例化时相当容易构建。

相关文章

网友评论

      本文标题:python类与对象详解(3):简化初始化过程

      本文链接:https://www.haomeiwen.com/subject/itgalttx.html