Changeset 391 for python/trunk/Doc/tutorial/classes.rst
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Doc/tutorial/classes.rst
r2 r391 5 5 ******* 6 6 7 Python's class mechanism adds classes to the language with a minimum of new 8 syntax and semantics. It is a mixture of the class mechanisms found in C++ and 9 Modula-3. As is true for modules, classes in Python do not put an absolute 10 barrier between definition and user, but rather rely on the politeness of the 11 user not to "break into the definition." The most important features of classes 12 are retained with full power, however: the class inheritance mechanism allows 7 Compared with other programming languages, Python's class mechanism adds classes 8 with a minimum of new syntax and semantics. It is a mixture of the class 9 mechanisms found in C++ and Modula-3. Python classes provide all the standard 10 features of Object Oriented Programming: the class inheritance mechanism allows 13 11 multiple base classes, a derived class can override any methods of its base 14 12 class or classes, and a method can call the method of a base class with the same 15 name. Objects can contain an arbitrary amount of data. 16 17 In C++ terminology, all class members (including the data members) are *public*, 18 and all member functions are *virtual*. As in Modula-3, there are no shorthands 19 for referencing the object's members from its methods: the method function is 20 declared with an explicit first argument representing the object, which is 21 provided implicitly by the call. As in Smalltalk, classes themselves are 22 objects. This provides semantics for importing and renaming. Unlike C++ and 23 Modula-3, built-in types can be used as base classes for extension by the user. 24 Also, like in C++, most built-in operators with special syntax (arithmetic 25 operators, subscripting etc.) can be redefined for class instances. 13 name. Objects can contain arbitrary amounts and kinds of data. As is true for 14 modules, classes partake of the dynamic nature of Python: they are created at 15 runtime, and can be modified further after creation. 16 17 In C++ terminology, normally class members (including the data members) are 18 *public* (except see below :ref:`tut-private`), and all member functions are 19 *virtual*. As in Modula-3, there are no shorthands for referencing the object's 20 members from its methods: the method function is declared with an explicit first 21 argument representing the object, which is provided implicitly by the call. As 22 in Smalltalk, classes themselves are objects. This provides semantics for 23 importing and renaming. Unlike C++ and Modula-3, built-in types can be used as 24 base classes for extension by the user. Also, like in C++, most built-in 25 operators with special syntax (arithmetic operators, subscripting etc.) can be 26 redefined for class instances. 26 27 27 28 (Lacking universally accepted terminology to talk about classes, I will make … … 65 66 implemented as Python dictionaries, but that's normally not noticeable in any 66 67 way (except for performance), and it may change in the future. Examples of 67 namespaces are: the set of built-in names ( functions such as :func:`abs`, and68 namespaces are: the set of built-in names (containing functions such as :func:`abs`, and 68 69 built-in exception names); the global names in a module; and the local names in 69 70 a function invocation. In a sense the set of attributes of an object also form … … 409 410 410 411 Methods may reference global names in the same way as ordinary functions. The 411 global scope associated with a method is the module containing the class412 definition. ( The class itselfis never used as a global scope.) While one412 global scope associated with a method is the module containing its 413 definition. (A class is never used as a global scope.) While one 413 414 rarely encounters a good reason for using global data in a method, there are 414 415 many legitimate uses of the global scope: for one thing, functions and modules … … 518 519 519 520 With new-style classes, dynamic ordering is necessary because all cases of 520 multiple inheritance exhibit one or more diamond relationships (where oneat521 multiple inheritance exhibit one or more diamond relationships (where at 521 522 least one of the parent classes can be accessed through multiple paths from the 522 523 bottommost class). For example, all new-style classes inherit from … … 534 535 .. _tut-private: 535 536 536 Private Variables 537 ================= 537 Private Variables and Class-local References 538 ============================================ 538 539 539 540 "Private" instance variables that cannot be accessed except from inside an 540 object ,don't exist in Python. However, there is a convention that is followed541 object don't exist in Python. However, there is a convention that is followed 541 542 by most Python code: a name prefixed with an underscore (e.g. ``_spam``) should 542 543 be treated as a non-public part of the API (whether it is a function, a method … … 553 554 occurs within the definition of a class. 554 555 556 Name mangling is helpful for letting subclasses override methods without 557 breaking intraclass method calls. For example:: 558 559 class Mapping: 560 def __init__(self, iterable): 561 self.items_list = [] 562 self.__update(iterable) 563 564 def update(self, iterable): 565 for item in iterable: 566 self.items_list.append(item) 567 568 __update = update # private copy of original update() method 569 570 class MappingSubclass(Mapping): 571 572 def update(self, keys, values): 573 # provides new signature for update() 574 # but does not break __init__() 575 for item in zip(keys, values): 576 self.items_list.append(item) 577 555 578 Note that the mangling rules are designed mostly to avoid accidents; it still is 556 579 possible to access or modify a variable that is considered private. This can … … 587 610 passed a class that emulates the methods of that data type instead. For 588 611 instance, if you have a function that formats some data from a file object, you 589 can define a class with methods :meth:`read` and :meth:` readline` that get the612 can define a class with methods :meth:`read` and :meth:`!readline` that get the 590 613 data from a string buffer instead, and pass it as an argument. 591 614 … … 666 689 print char 667 690 for line in open("myfile.txt"): 668 print line 691 print line, 669 692 670 693 This style of access is clear, concise, and convenient. The use of iterators 671 694 pervades and unifies Python. Behind the scenes, the :keyword:`for` statement 672 695 calls :func:`iter` on the container object. The function returns an iterator 673 object that defines the method :meth:`next` which accesses elements in the 674 container one at a time. When there are no more elements, :meth:`next` raises a 675 :exc:`StopIteration` exception which tells the :keyword:`for` loop to terminate. 696 object that defines the method :meth:`~iterator.next` which accesses elements 697 in the container one at a time. When there are no more elements, 698 :meth:`~iterator.next` raises a :exc:`StopIteration` exception which tells the 699 :keyword:`for` loop to terminate. 676 700 This example shows how it all works:: 677 701 … … 687 711 'c' 688 712 >>> it.next() 689 690 713 Traceback (most recent call last): 691 714 File "<stdin>", line 1, in ? … … 694 717 695 718 Having seen the mechanics behind the iterator protocol, it is easy to add 696 iterator behavior to your classes. Define a :meth:`__iter__` method which719 iterator behavior to your classes. Define an :meth:`__iter__` method which 697 720 returns an object with a :meth:`next` method. If the class defines 698 721 :meth:`next`, then :meth:`__iter__` can just return ``self``:: 699 722 700 723 class Reverse: 701 " Iterator for looping over a sequence backwards"724 """Iterator for looping over a sequence backwards.""" 702 725 def __init__(self, data): 703 726 self.data = data … … 711 734 return self.data[self.index] 712 735 713 >>> for char in Reverse('spam'): 736 :: 737 738 >>> rev = Reverse('spam') 739 >>> iter(rev) 740 <__main__.Reverse object at 0x00A1DB50> 741 >>> for char in rev: 714 742 ... print char 715 743 ... … … 735 763 for index in range(len(data)-1, -1, -1): 736 764 yield data[index] 765 766 :: 737 767 738 768 >>> for char in reverse('golf'):
Note:
See TracChangeset
for help on using the changeset viewer.