Static methods - How to call a method from another method?

做~自己de王妃 提交于 2019-12-02 14:48:02
jldupont

class.method should work.

class SomeClass:
  @classmethod
  def some_class_method(cls):
    pass

  @staticmethod
  def some_static_method():
    pass

SomeClass.some_class_method()
SomeClass.some_static_method()

How do I have to do in Python for calling an static method from another static method of the same class?

class Test() :
    @staticmethod
    def static_method_to_call()
        pass

    @staticmethod
    def another_static_method() :
        Test.static_method_to_call()

    @classmethod
    def another_class_method(cls) :
        cls.static_method_to_call()

NOTE - it looks like the question has changed some. The answer to the question of how you call an instance method from a static method is that you can't without passing an instance in as an argument or instantiating that instance inside the static method.

What follows is mostly to answer "how do you call a static method from another static method":

Bear in mind that there is a difference between static methods and class methods in Python. A static method takes no implicit first argument, while a class method takes the class as the implicit first argument (usually cls by convention). With that in mind, here's how you would do that:

If it's a static method:

test.dosomethingelse()

If it's a class method:

cls.dosomethingelse()
Ahmad Dwaik

OK the main difference between class methods and static methods is:

  • class method has its own identity, that's why they have to be called from within an INSTANCE.
  • on the other hand static method can be shared between multiple instances so that it must be called from within THE CLASS
Ahmad Dwaik

you cant call non-static methods from static methods but by creating an instance inside the static method.... it should work like that

class test2(object):
    def __init__(self):
        pass

    @staticmethod
    def dosomething():
        print "do something"
        #creating an instance to be able to call dosomethingelse(),or you may use any existing instace
        a=test2()
        a.dosomethingelse()

    def dosomethingelse(self):
        print "do something else"

test2.dosomething()

hope that will help you :)

If these don't depend on the class or instance then why not just make them a function? As this would seem like the obvious solution. Unless of course you think it's going to need to be overwritten, subclass etc. If so then the previous answers are the best bet. Fingers crossed I wont get marked down for merely offering an alternative solution that may or may not fit someones needs ;).

As the correct answer will depend on the use case of the code in question ;) Enjoy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!