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
  • 171,228
  • 44
  • 289
  • 238
Shon Freelen
  • 359
  • 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
  • 171,228
  • 44
  • 289
  • 238
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 The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
Louis
  • 2,854
  • 2
  • 19
  • 24
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
  • 23,742
  • 18
  • 63
  • 67