Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class method with static and not-static overloads

Tags:

python

I have a Python class MyClass with a method do_something. I would like this method to have an optional parameter some_param. So far the code looks like this:

class MyClass(object):

    def __init__(self, some_param)
        self.some_param = some_param

    def do_something(some_param=None):
        if some_param:
            pass
        else:
            some_param = self.some_param

    @staticmethod
    def do_something_static(some_param):
        pass

is it possible to have the do_something_static and do_something have the same name?

In other words:

if some_param is provided I would like do_something to be a static method.

If some_param is not provided, then it would not be a static method since it needs to access self.some_param.

MyClass needs to have both functionalities and I'd like to have them in a single function, callable both as a static method and as a non-static one: is it possible?


why? I'd rather not have different functions doing the same thing. do_something_static really sounds like "I didn't know how to do it any better". What I'm asking is if it possible to access self in a static method, given that I won't do that if it is called with the needed parameter that replaces self.

like image 702
Saturnix Avatar asked Sep 06 '25 18:09

Saturnix


1 Answers

If I understand correctly, you want to have a function that, if it's called as a method will take it's argument from an attribute of self, but otherwise just uses its single argument directly. You can do this in Python 3, where unbound methods are plain old functions (but not in Python 2, where unbound methods require their first argument be an instance).

Here's a quick example:

class MyClass:
    def func(arg):
        if isinstance(arg, MyClass):
            # if we were called as arg.func(), get the actual arg value from an attribute
            arg = arg.some_attribute

        # do something with arg
        print(arg)

# MyClass.func can be called like a static method
MyClass.func("foo")

# or as a method of an instance of MyClass
instance = MyClass()
instance.some_attribute = "bar"
instance.func()

Now, I suppose this won't do what you want if the argument you pass to the static method might be an instance of the class (which the code above will mis-recognize as calling the method on the instance). I don't think there's a good way around that that wouldn't require a lot of work with descriptors.

like image 157
Blckknght Avatar answered Sep 08 '25 06:09

Blckknght