I\'m wondering if it\'s possible to make a method which behaves differently when called as a class method than when called as an instance method.
For example, as a skill
[edited: use attribute to be a more direct answer; see the helpful comment by John Fouhy]
You can use a descriptor to do what you want:
class cls_or_inst_method(object):
def __init__(self, class_method, instance_method):
self.class_method = class_method
self.instance_method = instance_method
def __get__(self, obj, objtype):
if obj is None:
return self.class_method
else:
return lambda: self.instance_method(obj)
def my_class_method(baz):
return baz + 1
def my_instance_method(self):
return self.baz * 2
class Foo(object):
baz = 10
bar = cls_or_inst_method(my_class_method, my_instance_method)
Using the above:
>>> print Foo.bar(5)
6
>>> my_foo = Foo()
>>> print my_foo.bar()
20