0

I am novice to python and I am trying to learn the concept of classes. There are some some questions I want to ask:

  1. Is it mandatory to write __init__(self) constructor?
  2. How do you run a script that has classes?
  3. 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
2
  • Check the indent of the last line. Something looks "off", no? (In Python, self is just a parameter, and thus only applies to the given function scope which is determined by the indent.) Commented Feb 27, 2014 at 5:39
  • 2. Just like any other script. Commented Feb 27, 2014 at 9:53

1 Answer 1

2

1) No, it's not mandatory. Constructor are usually used for initialization. If you implement a constructor or not, depends on what you are trying to do.

3) It seems like it's an indentation issue:

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
Sign up to request clarification or add additional context in comments.

3 Comments

2. How to run a script that have classes and many functions in one go
The answer to that question can be found in any book (or tutorial) about OOP in Python.
@user3201916 If the correct indentation solved your problem which should be the case here you should accept the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.