I have class Books
and method select
in it. Also there is an instance of that class called book
. I want to be able to do both Bo
You could use a descriptor:
class Select(object):
def __get__(self,obj,objtype):
x=objtype if obj is None else obj
def select(where):
print(x,where)
return select
class Books(object):
select=Select()
book = Books()
Books.select(where='asdf')
book.select(where='asdf')
yields
<class '__main__.Books'> asdf
<__main__.Books object at 0xb7696dec> asdf
Solution using a descriptor and a decorator:
class class_or_instance_method():
def __init__(self, method):
self.method = method
def __get__(self, obj, objtype):
x = obj or objtype
def wrapped(*args, **kwargs):
return self.method(x, *args, **kwargs)
return wrapped
class Books():
@class_or_instance_method
def select(obj, where):
print(obj, where)
book = Books()
Books.select(where='asdf')
book.select(where='asdf')
Result:
<class '__main__.Books'> asdf
<__main__.Books object at 0x2695890> asdf
Just an example I founded on http://code.activestate.com/recipes/52304-static-methods-aka-class-methods-in-python/
You create a little wrapper:
class Callable:
def __init__(self, anycallable):
self.__call__ = anycallable
And then defines your class and a class variable inside it.
class Class2:
def static2(name):
print "Hi there",name
static2 = Callable(static2)
# now, a call such as:
Class2.static2("Peter")
# works just fine, and as-expected