使用构建器模式,我得到了attributeError:' noneType'对象没有属性属于构建器类功能
我尝试实例我使用构建器模式进行的类
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()
我认为这两个代码都是正确的,但是#Error版本不起作用。 我该如何修复?
I try to instance my class that made by using builder pattern
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
then I use below code to run 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()
I think both of code is right, but #error version is not working..
How can I fix it??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我得到了答案!
我必须附加
返回self
代码如下:I got my answer!
I have to append
return self
code like below: