Builder pattern equivalent in Python

前端 未结 6 548
余生分开走
余生分开走 2020-12-23 09:00

In Java, you can use the builder pattern to provide a more readable means to instantiating a class with many parameters. In the builder pattern, one constructs a configurati

6条回答
  •  不知归路
    2020-12-23 09:44

    I disagree with @MechanicalSnail. I think a builder implementation similar to one referenced by the poster is still very useful in some cases. Named parameters will only allow you to simply set member variables. If you want to do something slightly more complicated, you're out of luck. In my example I use the classic builder pattern to create an array.

    class Row_Builder(object):
      def __init__(self):
        self.row = ['' for i in range(170)]
    
      def with_fy(self, fiscal_year):
        self.row[FISCAL_YEAR] = fiscal_year
        return self
    
      def with_id(self, batch_id):
        self.row[BATCH_ID] = batch_id
        return self
    
      def build(self):
        return self.row
    

    Using it:

    row_FY13_888 = Row_Builder().with_fy('FY13').with_id('888').build()
    

提交回复
热议问题