Python - Class with independent method

Introduction

Even methods, normally created by a def nested in a class, can be created completely independently of any class object.

The following, for example, defines a simple function outside of any class that takes one argument:

Demo

def uppername(obj): 
   return obj.name.upper()       # Still needs a self argument (obj) 
# w  w w  .  ja v  a 2 s  .com
class rec: pass              # Empty namespace object 
rec.name = 'Bob'             # Just objects with attributes 
rec.age  = 40 

rec.method = uppername            # Now it's a class's method! 

d = rec.method(rec)                     # Can call through instance or class 
print( d )

Result

Related Topic