mirror of
https://github.com/kennethreitz/dive-into-python3.git
synced 2026-06-05 15:00:18 +00:00
clarify first-class objects
This commit is contained in:
@@ -216,7 +216,7 @@ SyntaxError: non-keyword arg after keyword arg</samp></pre>
|
||||
<h3 id=whatsanobject>What’s An Object?</h3>
|
||||
<p>Everything in Python is an object, and everything can have attributes and methods. All functions have a built-in attribute <code>__doc__</code>, which returns the <var>docstring</var> defined in the function’s source code. The <code>sys</code> module is an object which has (among other things) an attribute called <var>path</var>. And so forth.
|
||||
<p>Still, this doesn’t answer the more fundamental question: what is an object? Different programming languages define “object” in different ways. In some, it means that <em>all</em> objects <em>must</em> have attributes and methods; in others, it means that all objects are subclassable. In Python, the definition is looser. Some objects have neither attributes nor methods, <em>but they could</em>. Not all objects are subclassable. But everything is an object in the sense that it can be assigned to a variable or passed as an argument to a function.
|
||||
<p>You may have heard the term “first-class object” in other programming contexts. In Python, functions are <i>first-class objects</i>. You can pass a function as an argument to another function. Modules are objects. You can pass an entire module as an argument to a function. Classes are objects, and individual instances of a class are also objects.
|
||||
<p>You may have heard the term “first-class object” in other programming contexts. In Python, functions are <i>first-class objects</i>. You can pass a function as an argument to another function. Modules are <i>first-class objects</i>. You can pass an entire module as an argument to a function. Classes are first-class objects, and individual instances of a class are also first-class objects.
|
||||
<p>This is important, so I’m going to repeat it in case you missed it the first few times: <em>everything in Python is an object</em>. Strings are objects. Lists are objects. Functions are objects. Classes are objects. Class instances are objects. Even modules are objects.
|
||||
<h2 id=indentingcode>Indenting Code</h2>
|
||||
<p>Python functions have no explicit <code>begin</code> or <code>end</code>, and no curly braces to mark where the function code starts and stops. The only delimiter is a colon (<code>:</code>) and the indentation of the code itself.
|
||||
|
||||
Reference in New Issue
Block a user