Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Initialize an instance - (not a constructor), attributes and getters

  • init
  • self

In Python we dont explicitely declare attributes so what people usually do is add a method calles __init__ and let that method set up the initial values of the insance-object.

class Point:
    def __init__(self, a, b):
        self.x = a
        self.y = b

from shapes import Point

p1 = Point(2, 3)
print(p1)          # <shapes.Point instance at 0x7fb58c31ccb0>
print(p1.x)        # 2
print(p1.y)        # 3

p2 = Point(b=7, a=8)
print(p2)          # <shapes.Point instance at 0x7fb58c31cd00>
print(p2.x)        # 8
print(p2.y)        # 7