I am novice to python and I am trying to learn the concept of classes. There are some some questions I want to ask:
- Is it mandatory to write
__init__(self)constructor? - How do you run a script that has classes?
- In this example, it is throwing an error for
self?
Code:
#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
Error:
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
selfis just a parameter, and thus only applies to the given function scope which is determined by the indent.)