7

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?

Nathan Basanese
  • 8,475
  • 10
  • 37
  • 66
hugh
  • 77
  • 1
  • 1
  • 4

4 Answers4

19
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.

Lukáš Lalinský
  • 40,587
  • 6
  • 104
  • 126
unwind
  • 391,730
  • 64
  • 469
  • 606
  • thanks if possible can someone explain it so i can understand it and learn it – hugh Oct 20 '09 at 09:31
  • 1
    Technically \_\_init\_\_ is not the constructor, \_\_new\_\_ is; see http://stackoverflow.com/questions/6130644/what-is-the-difference-between-a-constructer-and-initializer-in-python The object already exists when \_\_init\_\_ is called, which initializes its fields. – Max Wallace Dec 10 '13 at 18:01
6

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

kabirbaidhya
  • 3,264
  • 3
  • 34
  • 59
Beku
  • 395
  • 3
  • 8
2

See the Python tutorial.

Lukáš Lalinský
  • 40,587
  • 6
  • 104
  • 126
-4
class MyClass(SuperClass):
    def __init__(self, *args, **kwargs):
        super(MyClass, self).__init__(*args, **kwargs)
        # do initialization
giolekva
  • 1,158
  • 2
  • 11
  • 23