Classes provide a means of bundling data and functionality together. Creatinga new class creates a new type of object, allowing new instances of thattype to be made. Each class instance can have attributes attached to it formaintaining its state. Class instances can also have methods (defined by itsclass) for modifying its state.
Dungeons and Dragons (D&D) Fifth Edition (5e) Classes. A comprehensive list of all official character classes for Fifth Edition. Online photography courses are a flexible way to improve your photography skills. Watch online photography classes taught by world-class photographers today.
- MasterClass gives you access to genius through online classes from the best in the world.
- Classes + Events Online. Join us for FREE classes on Zoom. Adults and teens (ages 13 and up) are invited to learn new skills from talented makers in Community Classroom Online, while kids ages 3 and up can try new projects in Kids Club® Online.
- Note: To securely and completely log out of your NYU account when done, NYU recommends that you quit your web browser, especially when using a shared computer.
Compared with other programming languages, Python’s class mechanism adds classeswith a minimum of new syntax and semantics. It is a mixture of the classmechanisms found in C++ and Modula-3. Python classes provide all the standardfeatures of Object Oriented Programming: the class inheritance mechanism allowsmultiple base classes, a derived class can override any methods of its baseclass or classes, and a method can call the method of a base class with the samename. Objects can contain arbitrary amounts and kinds of data. As is true formodules, classes partake of the dynamic nature of Python: they are created atruntime, and can be modified further after creation.
In C++ terminology, normally class members (including the data members) arepublic (except see below Private Variables), and all member functions arevirtual. As in Modula-3, there are no shorthands for referencing the object’smembers from its methods: the method function is declared with an explicit firstargument representing the object, which is provided implicitly by the call. Asin Smalltalk, classes themselves are objects. This provides semantics forimporting and renaming. Unlike C++ and Modula-3, built-in types can be used asbase classes for extension by the user. Also, like in C++, most built-inoperators with special syntax (arithmetic operators, subscripting etc.) can beredefined for class instances.
(Lacking universally accepted terminology to talk about classes, I will makeoccasional use of Smalltalk and C++ terms. I would use Modula-3 terms, sinceits object-oriented semantics are closer to those of Python than C++, but Iexpect that few readers have heard of it.)
9.1. A Word About Names and Objects¶
Objects have individuality, and multiple names (in multiple scopes) can be boundto the same object. This is known as aliasing in other languages. This isusually not appreciated on a first glance at Python, and can be safely ignoredwhen dealing with immutable basic types (numbers, strings, tuples). However,aliasing has a possibly surprising effect on the semantics of Python codeinvolving mutable objects such as lists, dictionaries, and most other types.This is usually used to the benefit of the program, since aliases behave likepointers in some respects. For example, passing an object is cheap since only apointer is passed by the implementation; and if a function modifies an objectpassed as an argument, the caller will see the change — this eliminates theneed for two different argument passing mechanisms as in Pascal.
9.2. Python Scopes and Namespaces¶
Before introducing classes, I first have to tell you something about Python’sscope rules. Class definitions play some neat tricks with namespaces, and youneed to know how scopes and namespaces work to fully understand what’s going on.Incidentally, knowledge about this subject is useful for any advanced Pythonprogrammer.
Let’s begin with some definitions.
A namespace is a mapping from names to objects. Most namespaces are currentlyimplemented as Python dictionaries, but that’s normally not noticeable in anyway (except for performance), and it may change in the future. Examples ofnamespaces are: the set of built-in names (containing functions such as 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.
By the way, I use the word attribute for any name following a dot — forexample, in the expression 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! 1
Attributes may be read-only or writable. In the latter case, assignment toattributes is possible. Module attributes are writable: you can writemodname.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
.
Namespaces are created at different moments and have different lifetimes. Thenamespace containing the built-in names is created when the Python interpreterstarts up, and is never deleted. The global namespace for a module is createdwhen the module definition is read in; normally, module namespaces also lastuntil the interpreter quits. The statements executed by the top-levelinvocation of the interpreter, either read from a script file or interactively,are considered part of a module called __main__
, so they have their ownglobal namespace. (The built-in names actually also live in a module; this iscalled builtins
.)
The local namespace for a function is created when the function is called, anddeleted when the function returns or raises an exception that is not handledwithin the function. (Actually, forgetting would be a better way to describewhat actually happens.) Of course, recursive invocations each have their ownlocal namespace.
A scope is a textual region of a Python program where a namespace is directlyaccessible. “Directly accessible” here means that an unqualified reference to aname attempts to find the name in the namespace.
Although scopes are determined statically, they are used dynamically. At anytime during execution, there are 3 or 4 nested scopes whose namespaces aredirectly accessible:
the innermost scope, which is searched first, contains the local names
the scopes of any enclosing functions, which are searched starting with thenearest enclosing scope, contains non-local, but also non-global names
the next-to-last scope contains the current module’s global names
the outermost scope (searched last) is the namespace containing built-in names
If a name is declared global, then all references and assignments go directly tothe middle scope containing the module’s global names. To rebind variablesfound outside of the innermost scope, the 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).
Usually, the local scope references the local names of the (textually) currentfunction. Outside functions, the local scope references the same namespace asthe global scope: the module’s namespace. Class definitions place yet anothernamespace in the local scope.
It is important to realize that scopes are determined textually: the globalscope of a function defined in a module is that module’s namespace, no matterfrom where or by what alias the function is called. On the other hand, theactual search for names is done dynamically, at run time — however, thelanguage definition is evolving towards static name resolution, at “compile”time, so don’t rely on dynamic name resolution! (In fact, local variables arealready determined statically.)
A special quirk of Python is that – if no 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.
The 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.
9.2.1. Scopes and Namespaces Example¶
This is an example demonstrating how to reference the different scopes andnamespaces, and how global
and nonlocal
affect variablebinding:
The output of the example code is:
Note how the local assignment (which is default) didn’t change scope_test’sbinding of spam. The nonlocal
assignment changed scope_test’sbinding of spam, and the global
assignment changed the module-levelbinding.
You can also see that there was no previous binding for spam before theglobal
assignment.
9.3. A First Look at Classes¶
Classes introduce a little bit of new syntax, three new object types, and somenew semantics.
9.3.1. Class Definition Syntax¶
The simplest form of class definition looks like this:
Class definitions, like function definitions (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.)
In practice, the statements inside a class definition will usually be functiondefinitions, but other statements are allowed, and sometimes useful — we’llcome back to this later. The function definitions inside a class normally havea peculiar form of argument list, dictated by the calling conventions formethods — again, this is explained later.
When a class definition is entered, a new namespace is created, and used as thelocal scope — thus, all assignments to local variables go into this newnamespace. In particular, function definitions bind the name of the newfunction here.
When a class definition is left normally (via the end), a class object iscreated. This is basically a wrapper around the contents of the namespacecreated by the class definition; we’ll learn more about class objects in thenext section. The original local scope (the one in effect just before the classdefinition was entered) is reinstated, and the class object is bound here to theclass name given in the class definition header (ClassName
in theexample).
9.3.2. Class Objects¶
Class objects support two kinds of operations: attribute references andinstantiation.
Attribute references use the standard syntax used for all attribute referencesin Python: 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:
then 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'
.
Class instantiation uses function notation. Just pretend that the classobject is a parameterless function that returns a new instance of the class.For example (assuming the above class):
creates a new instance of the class and assigns this object to the localvariable x
.
The instantiation operation (“calling” a class object) creates an empty object.Many classes like to create objects with instances customized to a specificinitial state. Therefore a class may define a special method named__init__()
, like this:
When a class defines an __init__()
method, class instantiationautomatically invokes __init__()
for the newly-created class instance. Soin this example, a new, initialized instance can be obtained by:
Of course, the __init__()
method may have arguments for greaterflexibility. In that case, arguments given to the class instantiation operatorare passed on to __init__()
. For example,
9.3.3. Instance Objects¶
Now what can we do with instance objects? The only operations understood byinstance objects are attribute references. There are two kinds of validattribute names: data attributes and methods.
data attributes correspond to “instance variables” in Smalltalk, and to “datamembers” in C++. Data attributes need not be declared; like local variables,they spring into existence when they are first assigned to. For example, ifx
is the instance of MyClass
created above, the following piece ofcode will print the value 16
, without leaving a trace:
The other kind of instance attribute reference is a method. A method is afunction that “belongs to” an object. (In Python, the term method is not uniqueto class instances: other object types can have methods as well. For example,list objects have methods called append, insert, remove, sort, and so on.However, in the following discussion, we’ll use the term method exclusively tomean methods of class instance objects, unless explicitly stated otherwise.)
Valid method names of an instance object depend on its class. By definition,all attributes of a class that are function objects define correspondingmethods of its instances. So in our example, 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.
9.3.4. Method Objects¶
Usually, a method is called right after it is bound:
In the 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:
will continue to print helloworld
until the end of time.
What exactly happens when a method is called? You may have noticed thatx.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…
Actually, you may have guessed the answer: the special thing about methods isthat the instance object is passed as the first argument of the function. In ourexample, the call 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.
If you still don’t understand how methods work, a look at the implementation canperhaps clarify matters. When a non-data attribute of an instance isreferenced, the instance’s class is searched. If the name denotes a valid classattribute that is a function object, a method object is created by packing(pointers to) the instance object and the function object just found together inan abstract object: this is the method object. When the method object is calledwith an argument list, a new argument list is constructed from the instanceobject and the argument list, and the function object is called with this newargument list.
9.3.5. Class and Instance Variables¶
Generally speaking, instance variables are for data unique to each instanceand class variables are for attributes and methods shared by all instancesof the class:
As discussed in A Word About Names and Objects, shared data can have possibly surprisingeffects with involving mutable objects such as lists and dictionaries.For example, the tricks list in the following code should not be used as aclass variable because just a single list would be shared by all Doginstances:
Correct design of the class should use an instance variable instead:
9.4. Random Remarks¶
If the same attribute name occurs in both an instance and in a class,then attribute lookup prioritizes the instance:
Data attributes may be referenced by methods as well as by ordinary users(“clients”) of an object. In other words, classes are not usable to implementpure abstract data types. In fact, nothing in Python makes it possible toenforce data hiding — it is all based upon convention. (On the other hand,the Python implementation, written in C, can completely hide implementationdetails and control access to an object if necessary; this can be used byextensions to Python written in C.)
Clients should use data attributes with care — clients may mess up invariantsmaintained by the methods by stamping on their data attributes. Note thatclients may add data attributes of their own to an instance object withoutaffecting the validity of the methods, as long as name conflicts are avoided —again, a naming convention can save a lot of headaches here.
There is no shorthand for referencing data attributes (or other methods!) fromwithin methods. I find that this actually increases the readability of methods:there is no chance of confusing local variables and instance variables whenglancing through a method.
Often, the first argument of a method is called 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.
Any function object that is a class attribute defines a method for instances ofthat class. It is not necessary that the function definition is textuallyenclosed in the class definition: assigning a function object to a localvariable in the class is also ok. For example:
Now 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.
Methods may call other methods by using method attributes of the self
argument:
Methods may reference global names in the same way as ordinary functions. Theglobal scope associated with a method is the module containing itsdefinition. (A class is never used as a global scope.) While onerarely encounters a good reason for using global data in a method, there aremany legitimate uses of the global scope: for one thing, functions and modulesimported into the global scope can be used by methods, as well as functions andclasses defined in it. Usually, the class containing the method is itselfdefined in this global scope, and in the next section we’ll find some goodreasons why a method would want to reference its own class.
Classes Google Classroom
Each value is an object, and therefore has a class (also called its type).It is stored as object.__class__
.
9.5. Inheritance¶
Of course, a language feature would not be worthy of the name “class” withoutsupporting inheritance. The syntax for a derived class definition looks likethis:
The name 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:
Execution of a derived class definition proceeds the same as for a base class.When the class object is constructed, the base class is remembered. This isused for resolving attribute references: if a requested attribute is not foundin the class, the search proceeds to look in the base class. This rule isapplied recursively if the base class itself is derived from some other class.
There’s nothing special about instantiation of derived classes: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.
Derived classes may override methods of their base classes. Because methodshave no special privileges when calling other methods of the same object, amethod of a base class that calls another method defined in the same base classmay end up calling a method of a derived class that overrides it. (For C++programmers: all methods in Python are effectively virtual
.)
An overriding method in a derived class may in fact want to extend rather thansimply replace the base class method of the same name. There is a simple way tocall the base class method directly: just call 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.)
Python has two built-in functions that work with inheritance:
Use
isinstance()
to check an instance’s type:isinstance(obj,int)
will beTrue
only ifobj.__class__
isint
or some classderived fromint
.Use
issubclass()
to check class inheritance:issubclass(bool,int)
isTrue
sincebool
is a subclass ofint
. However,issubclass(float,int)
isFalse
sincefloat
is not asubclass ofint
.
9.5.1. Multiple Inheritance¶
Python supports a form of multiple inheritance as well. A class definition withmultiple base classes looks like this:
For most purposes, in the simplest cases, you can think of the search forattributes inherited from a parent class as depth-first, left-to-right, notsearching twice in the same class where there is an overlap in the hierarchy.Thus, if an attribute is not found in 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.
In fact, it is slightly more complex than that; the method resolution orderchanges dynamically to support cooperative calls to 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.
Dynamic ordering is necessary because all cases of multiple inheritance exhibitone or more diamond relationships (where at least one of the parent classescan be accessed through multiple paths from the bottommost class). For example,all classes inherit from 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/.
9.6. Private Variables¶
“Private” instance variables that cannot be accessed except from inside anobject don’t exist in Python. However, there is a convention that is followedby most Python code: a name prefixed with an underscore (e.g. _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.
Since there is a valid use-case for class-private members (namely to avoid nameclashes of names with names defined by subclasses), there is limited support forsuch a mechanism, called name mangling. Any identifier of the form__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.
Name mangling is helpful for letting subclasses override methods withoutbreaking intraclass method calls. For example:
The above example would work even if 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.
Note that the mangling rules are designed mostly to avoid accidents; it still ispossible to access or modify a variable that is considered private. This caneven be useful in special circumstances, such as in the debugger.
Notice that code passed to 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.
9.7. Odds and Ends¶
Sometimes it is useful to have a data type similar to the Pascal “record” or C“struct”, bundling together a few named data items. An empty class definitionwill do nicely:
A piece of Python code that expects a particular abstract data type can often bepassed a class that emulates the methods of that data type instead. Forinstance, if you have a function that formats some data from a file object, youcan define a class with methods read()
and readline()
that get thedata from a string buffer instead, and pass it as an argument.
Instance method objects have attributes, too: m.__self__
is the instanceobject with the method m()
, and m.__func__
is the function objectcorresponding to the method.
9.8. Iterators¶
By now you have probably noticed that most container objects can be looped overusing a for
statement:
This style of access is clear, concise, and convenient. The use of iteratorspervades and unifies Python. Behind the scenes, the 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:
Having seen the mechanics behind the iterator protocol, it is easy to additerator behavior to your classes. Define an __iter__()
method whichreturns an object with a __next__()
method. If the classdefines __next__()
, then __iter__()
can just return self
:
9.9. Generators¶
Classes In Python
Generators are a simple and powerful tool for creating iterators. Theyare written like regular functions but use the 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:
Anything that can be done with generators can also be done with class-basediterators as described in the previous section. What makes generators socompact is that the __iter__()
and __next__()
methodsare created automatically.
Another key feature is that the local variables and execution state areautomatically saved between calls. This made the function easier to write andmuch more clear than an approach using instance variables like self.index
and self.data
.
In addition to automatic method creation and saving program state, whengenerators terminate, they automatically raise StopIteration
. Incombination, these features make it easy to create iterators with no more effortthan writing a regular function.
9.10. Generator Expressions¶
Some simple generators can be coded succinctly as expressions using a syntaxsimilar to list comprehensions but with parentheses instead of square brackets.These expressions are designed for situations where the generator is used rightaway by an enclosing function. Generator expressions are more compact but lessversatile than full generator definitions and tend to be more memory friendlythan equivalent list comprehensions.
Examples:
Footnotes
Except for one thing. Module objects have a secret read-only attribute called__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.