self variable in Python vs class variable
<p>Can you please clarify about the perimeter variable in the below class.</p>

<p>I understand that the <code>self.vertices</code> is to a particular instance. Since <code>perimeter</code> is not defined with <code>self</code>, does that mean its a class variable here? Then is it not common to all the instances?</p>

<p>Is it not the right way to code the perimeter as <code>self.perimeter</code>, so its aptly declared to each instance?</p>

<p>This code is from a book.</p>

<h3>Polygon.py</h3>

<pre><code>import math
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def distance(self, p2):
        return math.sqrt((self.x-p2.x)**2 + (self.y-p2.y)**2)

class Polygon:
    def __init__(self):
        self.vertices = []
    def add_point(self, point):
        self.vertices.append((point))
    def perimeter(self):
        perimeter = 0
        points = self.vertices + [self.vertices[0]]
        for i in range(len(self.vertices)):
            perimeter += points[i].distance(points[i+1])
        return perimeter
</code></pre>



<pre><code>&gt;&gt;&gt; square = Polygon() 
&gt;&gt;&gt; square.add_point(Point(1,1)) 
&gt;&gt;&gt; square.add_point(Point(1,2)) 
&gt;&gt;&gt; square.add_point(Point(2,2)) 
&gt;&gt;&gt; square.add_point(Point(2,1)) 
&gt;&gt;&gt; square.perimeter() 
4.0 
</code></pre>

<p>New type</p>

<pre><code>import math
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def distance(self, p2):
        return math.sqrt((self.x-p2.x)**2 + (self.y-p2.y)**2)

class Polygon:
        def __init__(self):
            self.vertices = []
        def add_point(self, point):
            self.vertices.append((point))
        def perimetermethod(self):
            self.perimeter = 0
            points = self.vertices + [self.vertices[0]]
            for i in range(len(self.vertices)):
                self.perimeter += points[i].distance(points[i+1])
            return self.perimeter

if __name__=='__main__':
    p1 = Polygon()
    p1.add_point(Point(1,1))
    p1.add_point(Point(1,2))
    p1.add_point(Point(2,2))
    p1.add_point(Point(2,1))
    print(p1.perimetermethod())
</code></pre>
