这是我的剧本:
class shape:
def __init__(self, name):
self.name = name
def printMyself(self):
print 'I am a shape named %s.' % self.name
shape1 = shape(name = 'myFirstShape.')
shape2 = shape(name = 'mySecondShape.')
shape1.printMyself()
shape2.printMyself()
class polyCube(shape):
def __init__(self, name, length, width, height):
shape.__init__(name)
self.length = length
self.width = width
self.height = height
def printMyself(self):
shape.printMyself(self)
print 'I am also a cube with dimensions %.2f, %.2f, %.2f.' % (length, width, height)
class polySphere(shape):
def __init__(self, name, radius):
shape.__init__(name)
self.radius = radius
def printMyself(self):
shape.printMyself(self)
print 'I am also a sphere with dimensions of %.2f.' % (radius)
cube1 = polyCube('firstCube', 2.0, 1.0, 3.0)
cube2 = polyCube('secondCube', 3.0, 3.0, 3.0)
sphere1 = polySphere('firstSphere', 2.2)
sphere2 = polySphere('secondSphere', 3.5)
shape1 = shape('myShape')
cube1.printMyself()
cube2.printMyself()
sphere1.printMyself()
sphere2.printMyself()
我的错误:
# Error: TypeError: unbound method __init__() must be called with shape instance as first argument (got str instance instead) #
我不明白。 为什么我收到此错误消息? 解决方案是什么? 为什么?
谢谢!
答案 0 :(得分:1)
您的代码的工作版本,我已经解释了评论中的错误
class shape:
def __init__(self, name):
self.name = name
def printMyself(self):
print ('I am a shape named %s.' % self.name)
shape1 = shape(name = 'myFirstShape.')
shape2 = shape(name = 'mySecondShape.')
shape1.printMyself()
shape2.printMyself()
class polyCube(shape):
def __init__(self, name, length, width, height):
shape.__init__(self,name) #pass self here, you're calling parent's __init__() explicitly so you should pass self.
self.length = length
self.width = width
self.height = height
def printMyself(self):
shape.printMyself(self)
#use self.length ,self.width instead of just length,width etc
print ('I am also a cube with dimensions %.2f, %.2f, %.2f.' % (self.length, self.width, self.height))
class polySphere(shape):
def __init__(self, name, radius):
shape.__init__(self,name) #pass self here
self.radius = radius
def printMyself(self):
shape.printMyself(self)
print ('I am also a sphere with dimensions of %.2f.' % (self.radius)) #use self.radius here
cube1 = polyCube('firstCube', 2.0, 1.0, 3.0)
cube2 = polyCube('secondCube', 3.0, 3.0, 3.0)
sphere1 = polySphere('firstSphere', 2.2)
sphere2 = polySphere('secondSphere', 3.5)
shape1 = shape('myShape')
cube1.printMyself()
cube2.printMyself()
sphere1.printMyself()
sphere2.printMyself()
答案 1 :(得分:0)
通常,您应该发布完整回溯。它使调试变得更容易。问题(我假设来自复制/粘贴错误的缩进除外)是你打电话的时候:
shape.__init__(name)
从形状继承。
如果您查看shape.__init__
的“原型”,它看起来像shape.__init__(self,name)
- 这就是您应该使用的内容。错误即将发生,因为您传递name
(字符串),您应该传递self
(PolyCube
,因此继承shape
ASIDE
此外,在python 2.x中,最好始终从object
继承。 e.g:
class shape(object):
...
这允许您使用与新式类相关的所有优点。 (在python 3中,所有类都是新式类)