Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a method be used as either a staticmethod or instance method?

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.

like image 768
Jake Avatar asked Apr 28 '11 01:04

Jake


People also ask

What is difference between a method and an instance?

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.

Is a method an instance?

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.

Can static methods be called with instances?

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.

Can instances have methods?

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 .


1 Answers

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!

like image 70
Ian B. Avatar answered Sep 30 '22 03:09

Ian B.