0

I defined a two classes within one file. I was able to have it run after separating the classes into two files, but I wanted to know why the first attempt does not work.

The traceback read:

Traceback (most recent call last):
  File "Polygon.py", line 15, in <module>
    class Triangle(Polygon):
  File "Polygon.py", line 21, in Triangle
    print(self.sides)
NameError: name 'self' is not defined

and the bare bones of my code was as follows

class Polygon:
    def __init__(self, no_of_sides):
        self.n = no_of_sides
        self.sides = [0 for i in range(no_of_sides)]
class Triangle(Polygon):
    def __init__(self):
        Polygon.__init__(self,3)

It threw the same NameError when I ran this as the body of class Triangle

class Triangle(Polygon):
    self.a = 1
3
  • Self isn't in scope in the class body I expect. Commented Oct 5, 2018 at 4:09
  • It's unclear what you want exactly Commented Oct 5, 2018 at 4:12
  • Your traceback does not fit your code. The offending line does not exist. Commented Oct 5, 2018 at 4:18

1 Answer 1

1

It looks like what you are trying to do, is define a class attribute a in class Triangle. You don't need self to do that. self is used to access the object instance of a class.

If you would want to define a as an object attribute rather than a class attribute, you should do something like:

class Triangle(Polygon):
    def __init__(self):
        Polygon.__init__(self, 3)
        self.a = 1

In this case, a is only defined upon class instantiation and accessible as Triangle().a, or as self.a inside other object-scope methods.

And if you want to define a as a class attribute, simply do:

class Triangle(Polygon):
    a = 1

    def __init__(self):
        ...

In this case, a is defined upon class definition and accessible even before instantiation, as Triangle.a

Sign up to request clarification or add additional context in comments.

Comments

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.