See All Titles |
![]() ![]() Methods HandlingWhenever you have to write methods in your classes, always keep in mind that the namespace searching order for attributes and methods is instance, class, and base classes; and don't forget that self is always the first or only argument to be used in method headers. Accessing Unbounded MethodsThe next example shows what you should do in order to unbind a class method and use it outside the class definition. 1: obj = classname() 2: umethod = classname.methodname() 3: umethod(obj, args) Line 1: Creates a class instance object. Line 2: Creates an object that references the class method. The method is still unattached to the object at this stage. Line 3: Executes the class method by transporting the instance reference (obj) and the list of arguments (args). Note that the first argument to an unbound method must be an instance of the correct class, or an exception will be thrown. Handling Global Class VariablesThe next example defines a function that prints a class variable. Every time a new instance is created, Globalcount increases. >>> def printGlobalcount(): … print Globalcount.n … >>> class Couting: … n = 0 … def __init__(self): … Globalcount.n = Globalcount.n + 1 … >>> inc = Couting() >>> inc = Couting() >>> printGlobalcount() 2 The next code overwrites the class variable x when subclassing the baseclass class. >>> class baseclass: … x = 5 … def multiply(self, a): … return a * (self.__class__.x) … >>> class inherited(baseclass): … x = 9 … >>> x = inherited() >>> x.multiply(2) 18 After a method is defined, it uses the variable values that are associated to the current namespace. >>> class A: … n = 1 … def printn(self): … print self.n … >>> class B(A): … n = 2 … >>> class C(B): … n = 3 … >>> obj1 = C() >>> obj1.printn() 3 >>> obj2 = B() >>> obj2.printn() 2 Calling Methods from Other MethodsThe next code exposes how simple it is to create a method to call another method. >>> class c: … def funcx(self): … self.funcy() … def funcy(self): … print "Ni!" … >>> obj = c() >>> obj.funcx() Ni!
|
Index terms contained in this sectionaccessingunbounded method handling methods methods handling unbounded accessing object-oriented programming (OOP) handling methods programming object-oriented (OOP) handling methods unbounded methods accessing |
© 2002, O'Reilly & Associates, Inc. |