写一个课时出错

时间:2010-04-22 14:20:56

标签: python class

我正在http://www.sthurlow.com/python/lesson08/在线完成一个教程,我相信我理解类在python中是如何工作的,至少在某种程度上,但是当我运行这段代码时:

class Shape:
    def __init__(self,x,y):
        self.x = x
        self.y = y
    description = "This shape has not been described yet"
    author = "Nobody has claimed to make this shape yet"
    def area(self):
        return self.x * self.y
    def perimeter(self):
        return 2 * self.x + 2 * self.y
    def describe(self,text):
        self.description = text
    def authorName(self,text):
        self.author = text
    def scaleSize(self,scale):
        self.x = self.x * scale
    self.y = self.y * scale

我收到此错误:

Traceback (most recent call last):
  File "Y:/python/Shape.py", line 1, in -toplevel-
    class Shape:
  File "Y:/python/Shape.py", line 17, in Shape
    self.y = self.y * scale
NameError: name 'self' is not defined

任何帮助都会很棒

由于

理查德

4 个答案:

答案 0 :(得分:10)

你需要缩进最后一行。

def scaleSize(self,scale): 
    self.x = self.x * scale 
self.y = self.y * scale 

应该是

def scaleSize(self,scale): 
    self.x = self.x * scale 
    self.y = self.y * scale 

答案 1 :(得分:3)

代码的最后一部分是错误的,

def scaleSize(self,scale):
    self.x = self.x * scale
self.y = self.y * scale

注意缩进,这在Python中很重要。根据您现在所拥有的,意味着self.y = self.y * scale不是内部 scaleSize方法,并且self类未定义关键字Shape

您需要做的是正确缩进,

def scaleSize(self,scale):
    self.x = self.x * scale
    self.y = self.y * scale

答案 2 :(得分:1)

指示的行具有错误的缩进级别,因此它不在scaleSize()方法中。

答案 3 :(得分:1)

您需要将第17行与第16行对齐

你有:

def scaleSize(self,scale):
    self.x = self.x * scale
self.y = self.y * scale

必须:

def scaleSize(self,scale):
    self.x = self.x * scale
    self.y = self.y * scale

这就是python知道它们属于同一种方法的方式。