Skip to content Skip to sidebar Skip to footer

Can A Function Be Static And Non-static In Python 2

Lets say I have this class: class Test(object): def __init__(self, a): self.a = a def test(self, b): if isinstance(self, Test): return self.a +

Solution 1:

If you want something that will actually receive self if called on an instance, but can also be called on the class, writing your own descriptor type may be advisable:

import types

classClassOrInstanceMethod(object):
    def__init__(self, wrapped):
        self.wrapped = wrapped
    def__get__(self, instance, owner):
        if instance isNone:
            instance = owner
        return self.wrapped.__get__(instance, owner)

classdemo(object):
    @ClassOrInstanceMethoddeffoo(self):
        # self will be the class if this is called on the classprint(self)

Demo.

For the original version of your question, you could just write it like any other static method, with @staticmethod. Calling a static method on an instance works the same as calling it on the class:

classTest(object):
    @staticmethod
    def test(a, b):
        return a + b

Demo.

Post a Comment for "Can A Function Be Static And Non-static In Python 2"