changeset 19:017ab6a2c727

Added sections on properties and borrowed language elements.
author Atul Varma <varmaa@toolness.com>
date Thu, 05 Jun 2008 22:51:27 -0700
parents a63485ecad03
children 6dc91d39b055
files PythonForJsProgrammers.txt
diffstat 1 files changed, 48 insertions(+), 8 deletions(-) [+]
line wrap: on
line diff
--- a/PythonForJsProgrammers.txt	Thu Jun 05 22:10:53 2008 -0700
+++ b/PythonForJsProgrammers.txt	Thu Jun 05 22:51:27 2008 -0700
@@ -494,13 +494,40 @@
     >>> doThing()
     6
 
-Operator Overloading, Special Methods, and Properties
-=====================================================
+Properties
+==========
+
+You can achieve the equivalent of JavaScript's getters and setters by
+creating a ``property`` in a class definition:
+
+    >>> class Foo(object):
+    ...     def _get_bar(self):
+    ...         print "getting bar!"
+    ...         return 5
+    ...     bar = property(fget = _get_bar)
+
+Not quite as elegant as JavaScript's ``get`` keyword in an object
+initializer, but it gets the job done:
+
+    >>> f = Foo()
+    >>> f.bar
+    getting bar!
+    5
+
+Note that since we didn't define a setter, we've effectively created a
+read-only attribute:
+
+    >>> f.bar = 5
+    Traceback (most recent call last):
+    ...
+    AttributeError: can't set attribute
+
+Operator Overloading and Special Methods
+========================================
 
 Classes can define methods with special names to do all sorts of
-dynamic things, from operator overloading to custom properties and
-more.  Some of these dynamic features are available in JavaScript, and
-some aren't.  You can read about tehm more in the Python Reference
+dynamic things, from operator overloading to custom attribute access
+and more.  You can read about tehm more in the Python Reference
 Manual's section on `special method names`_.
 
 .. _`special method names`: http://docs.python.org/ref/specialnames.html
@@ -522,6 +549,22 @@
 
 .. _`built-in ones`: http://docs.python.org/lib/module-exceptions.html
 
+Borrowed Goods
+==============
+
+As mentioned at the beginning of this document, some of JavaScript's
+latest features have been borrowed directly from Python.
+
+`Generators`_, `iterators`_, and `generator expressions`_ work almost
+identically to their JavaScript 1.7 counterparts.  And while I'm not
+sure if Python was the inspiration for them, JavaScript 1.7's array
+comprehensions are almost identical to Python's `list comprehensions`_.
+
+.. _`Generators`: http://www.python.org/dev/peps/pep-0255/
+.. _`iterators`: http://docs.python.org/lib/typeiter.html
+.. _`generator expressions`: http://www.python.org/dev/peps/pep-0289/
+.. _`list comprehensions`: http://docs.python.org/tut/node7.html#SECTION007140000000000000000
+
 Coding Style
 ============
 
@@ -548,6 +591,3 @@
 =====
 
 TODO: Mention TinyPy.
-
-TODO: Mention generators, generator comprehensions/expressions, array
-comprehensions, other stuff lifted from Python by JS.