Quark's Outlines: Python User-defined Methods
Quark’s Outlines: Python User-Defined Methods Overview, Historical Timeline, Problems & Solutions An Overview of Python User-Defined Methods What is a Python user-defined method? When you define a function inside a class, Python does not treat it as just a function. When you call it from an instance, Python changes it into a method. This method knows which object it was called from. It adds that object as the first argument when the function runs. A Python user-defined method joins a function, a class, and a class instance (or None ). It is created when you get a function from a class or an instance. Python binds the instance to the function and forms a method. Python lets you bind a class function to an instance as a method. class Box : def show ( self , word ): print ( " Box says: " , word ) x = Box () x . show ( " hi " ) # prints: # Box says: hi The method x.show is bound to the instance x . Python passes x as the first argument. What does "bound method" mean in Python? When a method is bound, it remembers the instance that called it. A bound method is created when you get a method from an object. It holds a reference to both the function and the instance. Python will pass the instance automatically when you call the method. If you get the same method from the class, Python gives you an unbound method. That means the function is not tied to any one object. Python uses bound methods to remember which object to call with. class Lamp : def turn_on ( self ): print ( " The lamp is now on. " ) l = Lamp () m = Lamp () a = l . turn_on b = m . turn_on a () b () # prints: # The lamp is now on. # The lamp is now on. Each bound method remembers which Lamp it came from. A Historical Timeline of Python User-Defined Methods Where do Python user-defined methods come from? Python user-defined methods grew from early ideas in object-oriented design. In many languages, methods are just functions that get special treatment when called from an object. Python made this clear by lettin