Search code examples
pythonfunctionclassstatic-methodsinstances

Class Function and Static Method at the Same Time? (Python)


Is it possible to have a function that not only behaves like a @staticmethod wrapped function but also like any other class function so that if one calls the function through an instance, the data from the instance can be passed?

example:

class Amazing(object):
    @static_and_class
    def func(x):
        return type(x)

apple = Amazing()

>>> print(apple.func())
>>> <class 'Amazing'>
>>> print(Amazing.func(2))
>>> <class 'int'>

That's a basic example of the system. Basically, what I want is a way to pass information like instance data if possible, but if the data was not there the function would take the necessary variables to execute its program.

Thanks to anyone who can solve this!!


Solution

  • Any method of any class can be called through the class' name. An instance will automatically pass itself as the first parameter of any of its methods. So, if you have something like

    class Bar:
        def bar(self):
            return type(self)
    

    you can do

    thing = Bar()
    print(thing.bar())
    print(Bar.bar(2))
    

    and you will get

    <class '__main__.Bar'>
    <class 'int'>
    

    with no problems. This is, of course, frowned upon; when writing methods for instances, the method should be written such that self is presumed to be an instance of the class it is written for.