我试图实例化我的类,使用builder模式
class Cat:
def __init__(self,height,weight, color):
self.height = height
self.weight = weight
self.color = color
def print(self):
print("%d %d %s" %(self.height,self.weight,self.color))
class CatBuilder:
def __init__(self):
self.weight = None
self.height = None
self.color = None
def setWeight(self,weight):
self.weight = weight
def setHeight(self,height):
self.height = height
def setColor(self,color):
self.color = color
def build(self):
cat = Cat(self.height,self.weight,self.color)
return cat
然后我使用下面的代码运行cat1.print()
#error version
cat1 = CatBuilder().setColor("red").setHeight(190).setWeight(80)
cat1.print()
#correct version
cat_builder = CatBuilder()
cat_builder.setColor("red")
cat_builder.setHeight(180)
cat_builder.setWeight(50)
cat2 = cat_builder.build()
cat2.print()
我认为两个代码都是正确的,但是#错误版本不工作。我怎么能解决它??
我找到答案了!我必须像下面这样附加return self
代码:
class Cat:
def __init__(self,height,weight, color):
self.height = height
self.weight = weight
self.color = color
def print(self):
print("%d %d %s" %(self.height,self.weight,self.color))
class CatBuilder:
def __init__(self):
self.weight = None
self.height = None
self.color = None
def setWeight(self,weight):
self.weight = weight
return self
def setHeight(self,height):
self.height = height
return self
def setColor(self,color):
self.color = color
return self
def build(self):
cat = Cat(self.height,self.weight,self.color)
return cat