abs()
, andbuilt-in exception names); the global names in a module; and the local names ina function invocation. In a sense the set of attributes of an object also forma namespace. The important thing to know about namespaces is that there isabsolutely no relation between names in different namespaces; for instance, twodifferent modules may both define a function maximize
without confusion —users of the modules must prefix it with the module name.z.real
, real
is an attribute of the objectz
. Strictly speaking, references to names in modules are attributereferences: in the expression modname.funcname
, modname
is a moduleobject and funcname
is an attribute of it. In this case there happens to bea straightforward mapping between the module’s attributes and the global namesdefined in the module: they share the same namespace! 1modname.the_answer=42
. Writable attributes may also be deleted with thedel
statement. For example, delmodname.the_answer
will removethe attribute the_answer
from the object named by modname
.__main__
, so they have their ownglobal namespace. (The built-in names actually also live in a module; this iscalled builtins
.)nonlocal
statement can beused; if not declared nonlocal, those variables are read-only (an attempt towrite to such a variable will simply create a new local variable in theinnermost scope, leaving the identically named outer variable unchanged).global
or nonlocal
statement is in effect – assignments to names always go into the innermost scope.Assignments do not copy data — they just bind names to objects. The same is truefor deletions: the statement delx
removes the binding of x
from thenamespace referenced by the local scope. In fact, all operations that introducenew names use the local scope: in particular, import
statements andfunction definitions bind the module or function name in the local scope.global
statement can be used to indicate that particularvariables live in the global scope and should be rebound there; thenonlocal
statement indicates that particular variables live inan enclosing scope and should be rebound there.global
and nonlocal
affect variablebinding:nonlocal
assignment changed scope_test’sbinding of spam, and the global
assignment changed the module-levelbinding.global
assignment.def
statements) must beexecuted before they have any effect. (You could conceivably place a classdefinition in a branch of an if
statement, or inside a function.)ClassName
in theexample).obj.name
. Valid attribute names are all the names that were inthe class’s namespace when the class object was created. So, if the classdefinition looked like this:MyClass.i
and MyClass.f
are valid attribute references, returningan integer and a function object, respectively. Class attributes can also beassigned to, so you can change the value of MyClass.i
by assignment.__doc__
is also a valid attribute, returning the docstring belonging tothe class: 'Asimpleexampleclass'
.x
.__init__()
, like this:__init__()
method, class instantiationautomatically invokes __init__()
for the newly-created class instance. Soin this example, a new, initialized instance can be obtained by:__init__()
method may have arguments for greaterflexibility. In that case, arguments given to the class instantiation operatorare passed on to __init__()
. For example,x
is the instance of MyClass
created above, the following piece ofcode will print the value 16
, without leaving a trace:x.f
is a valid methodreference, since MyClass.f
is a function, but x.i
is not, sinceMyClass.i
is not. But x.f
is not the same thing as MyClass.f
— itis a method object, not a function object.MyClass
example, this will return the string 'helloworld'
.However, it is not necessary to call a method right away: x.f
is a methodobject, and can be stored away and called at a later time. For example:helloworld
until the end of time.x.f()
was called without an argument above, even though the functiondefinition for f()
specified an argument. What happened to the argument?Surely Python raises an exception when a function that requires an argument iscalled without any — even if the argument isn’t actually used…x.f()
is exactly equivalent to MyClass.f(x)
. Ingeneral, calling a method with a list of n arguments is equivalent to callingthe corresponding function with an argument list that is created by insertingthe method’s instance object before the first argument.self
. This is nothing morethan a convention: the name self
has absolutely no special meaning toPython. Note, however, that by not following the convention your code may beless readable to other Python programmers, and it is also conceivable that aclass browser program might be written that relies upon such a convention.f
, g
and h
are all attributes of class C
that refer tofunction objects, and consequently they are all methods of instances ofC
— h
being exactly equivalent to g
. Note that this practiceusually only serves to confuse the reader of a program.self
argument:object.__class__
.BaseClassName
must be defined in a scope containing thederived class definition. In place of a base class name, other arbitraryexpressions are also allowed. This can be useful, for example, when the baseclass is defined in another module:DerivedClassName()
creates a new instance of the class. Method referencesare resolved as follows: the corresponding class attribute is searched,descending down the chain of base classes if necessary, and the method referenceis valid if this yields a function object.virtual
.)BaseClassName.methodname(self,arguments)
. This is occasionally useful to clients as well. (Note that thisonly works if the base class is accessible as BaseClassName
in the globalscope.)isinstance()
to check an instance’s type: isinstance(obj,int)
will be True
only if obj.__class__
is int
or some classderived from int
.issubclass()
to check class inheritance: issubclass(bool,int)
is True
since bool
is a subclass of int
. However,issubclass(float,int)
is False
since float
is not asubclass of int
.DerivedClassName
, it is searchedfor in Base1
, then (recursively) in the base classes of Base1
,and if it was not found there, it was searched for in Base2
, and so on.super()
. Thisapproach is known in some other multiple-inheritance languages ascall-next-method and is more powerful than the super call found insingle-inheritance languages.object
, so any case of multiple inheritanceprovides more than one path to reach object
. To keep the base classesfrom being accessed more than once, the dynamic algorithm linearizes the searchorder in a way that preserves the left-to-right ordering specified in eachclass, that calls each parent only once, and that is monotonic (meaning that aclass can be subclassed without affecting the precedence order of its parents).Taken together, these properties make it possible to design reliable andextensible classes with multiple inheritance. For more detail, seehttps://www.python.org/download/releases/2.3/mro/._spam
) shouldbe treated as a non-public part of the API (whether it is a function, a methodor a data member). It should be considered an implementation detail and subjectto change without notice.__spam
(at least two leading underscores, at most one trailing underscore)is textually replaced with _classname__spam
, where classname
is thecurrent class name with leading underscore(s) stripped. This mangling is donewithout regard to the syntactic position of the identifier, as long as itoccurs within the definition of a class.MappingSubclass
were to introduce a__update
identifier since it is replaced with _Mapping__update
in theMapping
class and _MappingSubclass__update
in the MappingSubclass
class respectively.exec()
or eval()
does not consider theclassname of the invoking class to be the current class; this is similar to theeffect of the global
statement, the effect of which is likewise restrictedto code that is byte-compiled together. The same restriction applies togetattr()
, setattr()
and delattr()
, as well as when referencing__dict__
directly.read()
and readline()
that get thedata from a string buffer instead, and pass it as an argument.m.__self__
is the instanceobject with the method m()
, and m.__func__
is the function objectcorresponding to the method.for
statement:for
statementcalls iter()
on the container object. The function returns an iteratorobject that defines the method __next__()
which accesseselements in the container one at a time. When there are no more elements,__next__()
raises a StopIteration
exception which tells thefor
loop to terminate. You can call the __next__()
methodusing the next()
built-in function; this example shows how it all works:__iter__()
method whichreturns an object with a __next__()
method. If the classdefines __next__()
, then __iter__()
can just return self
:yield
statementwhenever they want to return data. Each time next()
is called on it, thegenerator resumes where it left off (it remembers all the data values and whichstatement was last executed). An example shows that generators can be triviallyeasy to create:__iter__()
and __next__()
methodsare created automatically.self.index
and self.data
.StopIteration
. Incombination, these features make it easy to create iterators with no more effortthan writing a regular function.__dict__
which returns the dictionary used to implement the module’snamespace; the name __dict__
is an attribute but not a global name.Obviously, using this violates the abstraction of namespace implementation, andshould be restricted to things like post-mortem debuggers.