Giter Site home page Giter Site logo

dsc-object-initialization-houston-ds-021720's Introduction

Object Initialization

Introduction

Now that you've begun to see OOP and class structures, it's time to investigate the __init__ method more. The __init__ method allows classes to have default behaviors and attributes.

Objectives

You will be able to:

  • Create instance variables in the __init__ method
  • Use default arguments in the __init__ method

Introducing __init__

By using the __init__ method, you can initialize instances of objects with defined attributes. Without this, attributes are not defined until other methods are called to populate these fields, or you set attributes manually. This can be problematic. For example, if you had tried to call the greet_passeneger() method from the previous lab without first setting the driver's first and last attributes, you would have encountered an error. Here's another example to demonstrate:

class Person:
    def set_name(self, name):
        self.name = name
    def set_job(self, job):
        self.job = job
bob = Person()

If we try to access an attribute before setting it we'll get an error.

bob.name
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-3-b123a67a06c2> in <module>()
----> 1 bob.name


AttributeError: 'Person' object has no attribute 'name'
bob.set_name('Bob')
bob.name
'Bob'

To avoid errors such as this, you can use the __init__ method to set attributes on instantiation.

class Person:
    def __init__(self, name, job):
        self.name = name
        self.job = job
bob = Person('Bob', 'Carpenter')
print(bob.name)
print(bob.job)
Bob
Carpenter

Written like this, these arguments then become required:

someone = Person()
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-8-1ac56b0c183e> in <module>()
----> 1 someone = Person()


TypeError: __init__() missing 2 required positional arguments: 'name' and 'job'

Setting default arguments in the __init__ method

To circumvent this, we can also define __init__ to have default arguments. This allows parameters to be specified if desired but are not required.

class Person:
    def __init__(self, name=None, job=None):
        self.name = name
        self.job = job
someone = Person()
print(someone.name)
print(someone.job)

print('\n')
governer = Person(job = 'Carpenter')
print(governer.name)
print(governer.job)

print('\n')
bob = Person('Bob', 'Carpenter')
print(bob.name)
print(bob.job)
None
None


None
Carpenter


Bob
Carpenter

Summary

In this lesson, you got a brief introduction to the __init__ method and how you can use it to set attributes when objects are initialized, including default parameters.

dsc-object-initialization-houston-ds-021720's People

Contributors

mas16 avatar mathymitchell avatar loredirick avatar sumedh10 avatar

Watchers

James Cloos avatar  avatar Mohawk Greene avatar Victoria Thevenot avatar Bernard Mordan avatar Otha avatar raza jafri avatar  avatar Joe Cardarelli avatar The Learn Team avatar  avatar  avatar Ben Oren avatar Matt avatar Antoin avatar Alex Griffith avatar  avatar Amanda D'Avria avatar  avatar Ahmed avatar Nicole Kroese  avatar Dominique De León avatar Kaeland Chatman avatar  avatar Lisa Jiang avatar Vicki Aubin avatar Maxwell Benton avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.