Home > Articles > Open Source > Python

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

4.2 Class Declarations

The basic form of a class statement is:

class name:
    suite

where name is the name of the class being declared and suite is a suite of statements to execute. All the statements in the suite of a class declaration are typically def statements, although they do not have to be.

The class declaration is an executable statement. Like a def statement, it creates an object and assigns it to the name in the current scope. The def statement creates a function object. The class statement creates a class object. But here is an important difference: The suite in a function is not executed until the function is called. The statements in a class declaration are executed while the class statement is being executed.

When a function is called, it is executed with its own local environment where local variables are stored. When the function returns, the local environment is discarded. Like a function, the statements in a class declaration are executed with the declaration's own local environment. Unlike a function, however, when the class statement finishes executing, the local environment is not thrown away. It is saved in the __dict__ dictionary of the class object. The suite of statements in a class declaration is executed to create a dictionary of class attributes, the names known in the class. In other object-oriented languages, these are known as class variables.

The most common statement to include in a class declaration is the def statement, which is used to create the "methods" that operate on instances of the class (which we discuss in the next section); but it is possible to execute other assignments as well.

When you want to get the value of one of these names, you can use the dot operator. The form ClassName.attribute gives you the value of the attribute defined in the class. For example:

>>> class W:
...     y=1
...
>>> W.y
1

creates a class named W and assigns the value 1 to an attribute y. Note that y is an attribute of the class object itself, not of instances of the class. More confusing still, we can get at class attributes through instances of the class as well as through the class object. The way to get an instance of a class is by calling the class as we would call a function. So:

>>> z=W()
>>> z.y
1

shows that we can also get the value of y through the instance, z, of the class W.

  • + Share This
  • 🔖 Save To Your Account