Python - Class with independent method


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:


def uppername(obj): 
   return       # Still needs a self argument (obj) 
# from   w  ww  . j  a  va 2 s  .c  o m
class rec: pass              # Empty namespace object = '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 )


Related Topic