0

I have a question about calling static methods in IronPython via class instance. Let's say I have next static method:

class SomeClass(object):
    def SomeMethod(number):
        return number + 10

SomeMethod = staticmethod(SomeMethod)

I can call this method via class instance without any problems:

instance = SomeClass()
instance.SomeMethod(1)

But what about case when I want to return some values from self object via static method. Consider next case: I initialized field of this class object with some value in constructor and want to return this value from static method. Then I should somehow provide dependency between my object and my static method. My class looks like this:

class SomeClass(object):
    def SomeMethod(self, number):
        return self._numberValue + number + 10

SomeMethod = staticmethod(SomeMethod)

    def __init__(self):
        self._numberValue = 10

I try to call my static method exactly the same way:

instance = SomeClass()
instance.SomeMethod(1)

But then I got error : 'SomeMethod() takes exactly 2 argumets (1 given)'. Is there possibility to provide connection between class object and static method? Or this just makes no sense?)

1 Answer 1

1

A "normal" (non-static) class method receives a reference to the instance (self) implicitely as first parameter.

If you define your method as static, you have to pass an instance explicitely:

instance = SomeClass()
instance.SomeMethod(instance, 1)

Note that self is not a magic keyword, it's just a convention. You could use any other name for that variable if that makes it clearer:

def SomeMethod(inst, number):
    return inst._numberValue + number + 10
SomeMethod = staticmethod(SomeMethod)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.