开发者

(Python) What is the proper nomenclature for this so I can search for and learn about it?

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.


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.


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/


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜