Constructors in Python

28,081

Solution 1

class MyClass(object):
  def __init__(self, x, y, angle):
    self.x = x
    self.y = y
    self.angle = angle

The constructor is always written as a function called __init__(). It must always take as its first argument a reference to the instance being constructed. This is typically called self. The rest of the arguments are up to the programmer.

The object on the first line is the superclass, i.e. this says that MyClass is a subclass of object. This is normal for Python class definitions.

You access fields (members) of the instance using the self. syntax.

Solution 2

Constructors are declared with __init__(self, other parameters), so in this case:

def __init__(self, x, y, angle):
    self.x = x
    self.y = y
    self.angle = angle

You can read more about this here: Class definition in python

Solution 3

See the Python tutorial.

Share:
28,081
hugh
Author by

hugh

Updated on April 02, 2020

Comments

  • hugh
    hugh about 4 years

    I need help in writing code for a Python constructor method.

    This constructor method would take the following three parameters:

    x, y, angle 
    

    What is an example of this?

  • hugh
    hugh over 14 years
    thanks if possible can someone explain it so i can understand it and learn it
  • John La Rooy
    John La Rooy over 14 years
    Often a constructor may have extra parameters that should not be passed on to the parent(s) constructor
  • Max Wallace
    Max Wallace over 10 years
    Technically __init__ is not the constructor, __new__ is; see stackoverflow.com/questions/6130644/… The object already exists when __init__ is called, which initializes its fields.
  • Nathan Basanese
    Nathan Basanese almost 9 years
    // , @giolekva Would you be willing to improve this'n?