Search code examples
pythonclassinheritanceself

problem with "self" operator when inheriting from a class i wrote


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

Solution

  • 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