Python Tutorial, Release 3.9.5 Any function object that is a class attribute defines a method for instances of that class. It is not necessary that the function definition is textually enclosed in the class definition: assigning a function object to a local variable in the class is also ok. For example: Now f , g and h are all attributes of class C that refer to function objects, and consequently they are all methods of instances of C — h being exactly equivalent to g . Note that this practice usually 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. The global scope associated with a method is the module containing its definition. (A class is never used as a global scope.) While one rarely encounters a good reason for using global data in a method, there are many legitimate uses of the global scope: for one thing, functions and modules imported into the global scope can be used by methods, as well as functions and classes defined in it. Usually, the class containing the method is itself defined in this global scope, and in the next section we’ll find some good reasons why a method would want to reference its own class. Each value is an object, and therefore has a class (also called its type ). It is stored as$_{object.__class__}$ . Of course, a language feature would not be worthy of the name “class” without supporting inheritance. The syntax for a derived class definition looks like this: The name$_{BaseClassName}$ must be defined in a scope containing the derived class definition. In place of a base class name, other arbitrary expressions are also allowed. This can be useful, for example, when the base class is defined in another module: 72 Chapter 9. Classes classDerivedClassName (modname .BaseClassName): classDerivedClassName (BaseClassName): <statement-1> . . . <statement-N > classBag : def __init__ (self): self.data =[] def add(self, x): self.data.append(x) def addtwice(self, x): self.add(x) self.add(x) # Function defined outside the class def f1(self, x, y): return min(x, x +y) classC : f =f1 def g(self): return 'hello world' h =g 9.5 Inheritance