Chapter 9. Classes 68 Python Tutorial, Release 3.9.5 9.3 A First Look at Classes 9.3.1 Class Definition Syntax Classes introduce a little bit of new syntax, three new object types, and some new semantics. The simplest form of class definition looks like this: Class definitions, like function definitions ( def statements) must be executed before they have any effect. (You could conceivably place a class definition in a branch of an$_{if}$ statement, or inside a function.) In practice, the statements inside a class definition will usually be function definitions, but other statements are allowed, and sometimes useful — we’ll come back to this later. The function definitions inside a class normally have a peculiar form of argument list, dictated by the calling conventions for methods — again, this is explained later. When a class definition is entered, a new namespace is created, and used as the local scope — thus, all assignments to local variables go into this new namespace. In particular, function definitions bind the name of the new function here. When a class definition is left normally (via the end), a class object is created. This is basically a wrapper around the contents of the namespace created by the class definition; we’ll learn more about class objects in the next section. The original local scope (the one in effect just before the class definition was entered) is reinstated, and the class object is bound here to the class name given in the class definition header ($_{ClassName}$ in the example). Class objects support two kinds of operations: attribute references and instantiation. Attribute references use the standard syntax used for all attribute references in Python: obj.name . Valid attribute names are all the names that were in the class’s namespace when the class object was created. So, if the class definition looked like this: then$_{MyClass.i}$and$_{MyClass.f}$are valid attribute references, returning an integer and a function object, respec- tively. Class attributes can also be assigned to, so you can change the value of$_{MyClass.i}$by assignment.$_{__doc__}$ is also a valid attribute, returning the docstring belonging to the class:$_{"A simple example class"}$ . Class instantiation uses function notation. Just pretend that the class object is a parameterless function that returns a new instance of the class. For example (assuming the above class): x =MyClass() creates a new instance of the class and assigns this object to the local variable$_{x}$. The instantiation operation (“calling” a class object) creates an empty object. Many classes like to create objects with instances customized to a specific initial state. Therefore a class may define a special method named$_{__init__()}$ , like this: classMyClass : """A simple example class""" i =12345 def f(self): return 'hello world' 9.3.2 Class Objects classClassName : <statement-1> . . . <statement-N >