I'd like to be able to do this:
class A(object):
@staticandinstancemethod
def B(self=None, x, y):
print self is None and "static" or "instance"
A.B(1,2)
A().B(1,2)
This seems like a problem that should have a simple solution, but I can't think of or find one.
Instance method are methods which require an object of its class to be created before it can be called. To invoke a instance method, we have to create an Object of the class in which the method is defined.
An instance method is a method that belongs to instances of a class, not to the class itself. To define an instance method, just omit static from the method heading. Within the method definition, you refer to variables and methods in the class by their names, without a dot.
A static method cannot access a class's instance variables and instance methods, because a static method can be called even when no objects of the class have been instantiated.
Instance methods need a class instance and can access the instance through self . Class methods don't need a class instance. They can't access the instance ( self ) but they have access to the class itself via cls . Static methods don't have access to cls or self .
It is possible, but please don't. I couldn't help but implement it though:
class staticandinstancemethod(object):
def __init__(self, f):
self.f = f
def __get__(self, obj, klass=None):
def newfunc(*args, **kw):
return self.f(obj, *args, **kw)
return newfunc
...and its use:
>>> class A(object):
... @staticandinstancemethod
... def B(self, x, y):
... print self is None and "static" or "instance"
>>> A.B(1,2)
static
>>> A().B(1,2)
instance
Evil!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With