我是python的新手,我正在努力学习类的概念。我想问一些问题:
__init__(self)
构造函数?self
引发了错误? 代码:
#An example of a class
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 "C:/Python27/cls.py", line 2, in <module>
class Shape:
File "C:/Python27/cls.py", line 18, in Shape
self.y = self.y * scale
NameError: name 'self' is not defined
答案 0 :(得分:2)
1)不,这不是强制性的。构造函数通常用于初始化。如果您实现了构造函数,则取决于您要执行的操作。
3)这似乎是一个缩进问题:
class Shape:
def __init__(self,x,y):
self.x = x
self.y = y
self.description = "This shape has not been described yet"
self.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