Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
C
cpython
Project overview
Project overview
Details
Activity
Releases
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
Analytics
Analytics
Repository
Value Stream
Wiki
Wiki
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Create a new issue
Commits
Issue Boards
Open sidebar
Kirill Smelkov
cpython
Commits
958e368a
Commit
958e368a
authored
Apr 07, 2009
by
Raymond Hettinger
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Add an example metaclass showing a use of __prepare__() as outlined in PEP 3115.
parent
a7e33fec
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
32 additions
and
0 deletions
+32
-0
Doc/reference/datamodel.rst
Doc/reference/datamodel.rst
+32
-0
No files found.
Doc/reference/datamodel.rst
View file @
958e368a
...
...
@@ -1541,6 +1541,38 @@ explored including logging, interface checking, automatic delegation, automatic
property creation, proxies, frameworks, and automatic resource
locking/synchronization.
Here is an example of a metaclass that uses an :class:`OrderedDict` to
remember the order that class members were defined::
class OrderedClass(type):
@classmethod
def __prepare__(metacls, name, bases, **kwds):
return collections.OrderedDict()
def __new__(cls, name, bases, classdict):
result = type.__new__(cls, name, bases, dict(classdict))
result.members = tuple(classdict)
return result
class A(metaclass=OrderedClass):
def one(self): pass
def two(self): pass
def three(self): pass
def four(self): pass
>>> A.members
('__module__', 'one', 'two', 'three', 'four')
When the class definition for *A* get executed, the first step is calling the
metaclass's :meth:`__prepare__` method which returns an empty
:class:`collections.OrderedDict`. That mapping records the methods and
attributes of *A* as they are defined within the body of the class statement.
Once those definitions are executed, the ordered dict is fully populated, and
then the metaclass's :meth:`__new__ ` method gets invoked. That method builds
the new type and saves the keys for the ordered dictionary in an attribute
called *members*.
.. _callable-types:
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment