How To Create A Constructor In Python

Flag Football For Dummies is here!  Get your game on and order your copy today!dummies logo Dummies AI Browse Book & Article Categories

Book & Article Categories

closeTechnologyAcademics & The ArtsHome, Auto, & HobbiesBody, Mind, & SpiritBusiness, Careers, & MoneyCollections

Collections

Explore all collectionscloseBYOB (Be Your Own Boss)Be a Rad DadCareer ShiftingContemplating the CosmosFor Those Seeking Peace of MindFor the Aspiring AficionadoFor the Budding Cannabis EnthusiastFor the College BoundFor the Exam-Season CrammerFor the Game Day PrepperCustom Solutionsdummies logo
  • Book & Article Categoriesforward arrow
  • Collectionsforward arrow
  • Custom Solutions
  • Dummies AI
  • forward arrowMain Menu
  • Book & Article Categories

  • Technology
  • Academics & The Arts
  • Home, Auto, & Hobbies
  • Body, Mind, & Spirit
  • Business, Careers, & Money
  • Dummies AI
  • forward arrowMain Menu
  • Book & Article Categories

  • Technology
  • Academics & The Arts
  • Home, Auto, & Hobbies
  • Body, Mind, & Spirit
  • Business, Careers, & Money
  • Dummies AI
  • forward arrowMain Menu
  • Collections

    Explore all collections
  • BYOB (Be Your Own Boss)
  • Be a Rad Dad
  • Career Shifting
  • Contemplating the Cosmos
  • For Those Seeking Peace of Mind
  • For the Aspiring Aficionado
  • For the Budding Cannabis Enthusiast
  • For the College Bound
  • For the Exam-Season Crammer
  • For the Game Day Prepper
  • Dummies AI
HomeTechnology ArticlesProgramming & Web Design ArticlesPython ArticlesHow to Create a Constructor in PythonByJohn Paul Mueller Updated2019-10-16 14:42:35From the bookNo items found.Share
Download E-BookPersonal Finance For DummiesExplore BookStatistical Analysis with Python For DummiesStatistical Analysis with Python For Dummies book cover Explore BookBuy NowSubscribe on PerlegoDownload E-BookPersonal Finance For DummiesExplore BookStatistical Analysis with Python For DummiesStatistical Analysis with Python For Dummies book coverExplore BookBuy NowSubscribe on PerlegoA constructor is a special kind of method that Python calls when it instantiates an object using the definitions found in your class. Python relies on the constructor to perform tasks such as initializing (assigning values to) any instance variables that the object will need when it starts. Constructors can also verify that there are enough resources for the object and perform any other start-up task you can think of.

The name of a constructor is always the same, __init__(). The constructor can accept arguments when necessary to create the object. When you create a class without a constructor, Python automatically creates a default constructor for you that doesn’t do anything. Every class must have a constructor, even if it simply relies on the default constructor. The following steps demonstrate how to create a constructor:

Open a Python Shell window.

You see the familiar Python prompt.

Type the following code (pressing Enter after each line and pressing Enter twice after the last line):

class MyClass: Greeting = " def __init__(self, Name="there"): self.Greeting = Name + "!" def SayHello(self): print("Hello {0}".format(self.Greeting))

This example provides your first example of function overloading. In this case, there are two versions of __init__(). The first doesn’t require any special input because it uses the default value for the Name of “there”. The second requires a name as an input. It sets Greeting to the value of this name, plus an exclamation mark.

Python doesn’t support true function overloading. Many strict adherents to strict Object-Oriented Programming (OOP) principles consider default values to be something different from function overloading. However, the use of default values obtains the same result, and it’s the only option that Python offers. In true function overloading, you see multiple copies of the same function, each of which could process the input differently.

Type MyInstance = MyClass() and press Enter.

Python creates an instance of MyClass named MyInstance.

Type MyInstance.SayHello() and press Enter.

Type MyInstance.SayHello() and press Enter.

Notice that this message provides the default, generic greeting.

Type MyInstance = MyClass(“Amy”) and press Enter.

Python creates an instance of MyClass named MyInstance.

Type MyInstance.SayHello() and press Enter.

Type MyInstance.SayHello() and press Enter.

Notice that this message provides a specific greeting.

Close the Python Shell window.

Good job!

About This Article

This article is from the book: 

No items found.

About the book author:

John Paul Mueller is a freelance author and technical editor. He has writing in his blood, having produced 100 books and more than 600 articles to date. The topics range from networking to home security and from database management to heads-down programming. John has provided technical services to both Data Based Advisor and Coast Compute magazines.

This article can be found in the category: 

PythonNo items found.Get a Subscription

Tag » What Is A Constructor In Python