0

Suppose I create a class with a static method and want to run that method from another classes method or script function.

What is the scope of the static method?

ex:

def Class myClass:

     @staticmethod
     def mystaticmethod(input):
          print("blah")

def scriptfunc():
     myClass.mystaticmethod()

Is this valid?

2
  • 2
    Did you try it? What happened when you tried it? Commented Mar 10, 2020 at 3:30
  • def Class myclass isn't valid Python Commented Mar 10, 2020 at 4:15

3 Answers 3

1

What you have is valid.

But too elaborate on the purpose of @staticmethod, here's Short answer:

Declaring a @staticmethod would mean 2 things:

  1. You don't care about the properties or attributes of a method as it's independent of other classes,
  2. You do not require creating an __init__ or a super method to override it's content or attributes, and doesn't require a subclass/parent class to handle itself.
Sign up to request clarification or add additional context in comments.

Comments

1

You can just do ClassName.methodName(), from anywhere where ClassName is accessible (so, in the same enclosing scope, or in another module after having imported ClassName.

Python has docs on namespace precedences, which you can read here. Suffice it to say; for objects in general, their 'private' namespace is entirely accessible via the dot operator, as long as the object itself is accessible. This includes all variables and functions defined directly within.

Comments

1

Both of the answers here seem to ignore that the first line is invalid Python code:

def Class myClass:

You probably meant to write this:

class myClass:

One thing to note is that the @staticmethod decorator is not necessary in this case:

In [111]: class myClass:
     ...:      def mystaticmethod(x):
     ...:           print("blah")
     ...:

In [112]: myClass.mystaticmethod(3)
blah

Adding it makes no difference:

In [113]: class myClass:
     ...:      @staticmethod
     ...:      def mystaticmethod(x):
     ...:           print("blah")
     ...:

In [114]: myClass.mystaticmethod(3)
blah

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.