2

Sorry for the poor title. I really have no idea how to describe this to a search engine to find out how it works.

class MyClass(object):
    def __init__(self, contents=None):
        self.contents = contents

Specifically, the contents=None parameter.

I've been studying Python for about 2 months now, and that part semi-blows my mind. Any help or redirection to a similar, previously asked question will be very appreciated.

agf
  • 160,324
  • 40
  • 275
  • 231
Shon Freelen
  • 329
  • 1
  • 2
  • 11

4 Answers4

8

That's a Default Argument Value for a Keyword Argument.

They're pretty straightforward, as long as they're not a mutable object like a list or dictionary.

Just in case it was the __init__ method throwing you off -- it's the instance method of a class that gets automatically called when the instance is created. Any arguments you pass when you call the class to create a new instance, like

myclass = MyClass(contents='the_contents')

or

myclass = MyClass('the_contents')

in your example, are passed to the __init__ method.

Community
  • 1
  • 1
agf
  • 160,324
  • 40
  • 275
  • 231
3

This just means that "contents" is a parameter to be passed on when creating an instance, and that it has a default value, "None", used when the parameter is not given.

Those two ways of creating instances produces the same thing :

 b = MyClass()

 c = MyClass(None)

The best reading about Python, from the beginning, is probably the "dive" http://diveintopython.net/

Shadow Wizard Says No More War
  • 64,101
  • 26
  • 136
  • 201
Louis
  • 2,826
  • 1
  • 18
  • 23
1

When you define a method you can assign default values for its arguments. In this example contents is None unless you pass other value to it in constructor.

aambrozkiewicz
  • 542
  • 3
  • 14
1

You're looking at Keyword Arguments. The link is to Python documentation which explains them in quite alot of detail.

saffsd
  • 22,766
  • 16
  • 61
  • 66