Customizing constructors in Python
We want to initialize instances of the Rectangle
class with the values of both width
and height
. After we create an instance of a class, Python automatically calls the __init__
method. Thus, we can use this method to receive both the width
and height
arguments. We can then use these arguments to initialize attributes with the same names. We can think of the __init__
method as the equivalent of a constructor in other object-oriented programming languages.
The following lines create a Rectangle
class and declare an __init__
method within the body of the class:
class Rectangle: def __init__(self, width, height): print("I'm initializing a new Rectangle instance.") self.width = width self.height = height
This method ...
Get JavaScript : Object-Oriented Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.