@staticmethod question

Please post any questions about developing your plugin here. Please use the search function before posting!
User avatar
BackRaw
Senior Member
Posts: 537
Joined: Sun Jul 15, 2012 1:46 am
Location: Germany
Contact:

@staticmethod question

Postby BackRaw » Thu Dec 14, 2017 9:16 am

Hi,

I have the following example class:

Syntax: Select all

class MyClass(object):

# ... some instance methods ...

@staticmethod
def my_static_method(value):
return value * 5

# Global instance for the class
my_class = MyClass()

# ...

# Since it's a static method, it should be called like this:
fifty = MyClass.my_static_method(10)

# But is it OK to do the following as well?
fifty = my_class.my_static_method(10)
The reason I'm asking is because I have the global instance anyway in my code, so it makes some kind of sense to use it instead of the class/type itself. How do you view this "issue"? Python doesn't really care as far as results go, but I'm not too sure if using the instance is "pythonic". Thanks!
User avatar
satoon101
Project Leader
Posts: 2697
Joined: Sat Jul 07, 2012 1:59 am

Re: @staticmethod question

Postby satoon101 » Thu Dec 14, 2017 9:55 am

I actually prefer the 2nd method. When calling static methods from within your class itself, which of these do you use:

Syntax: Select all

class MyClass(object):
def some_method(self):
# From the instance
value = self.my_static_method(4)

# From the class
value = MyClass.my_static_method(4)

I always use the first there, as well. You also have to ask yourself, especially if you "only" call this method from outside of the class (whether in the global scope, in a function, and/or within a method of another class), if the better option would be to make this a global function.

Static methods are essentially functions that are not directly available at the global level. I typically (pretty much exclusively) only use them from within the class itself and almost never (if at all) use them from the other ways described above.
Image
User avatar
satoon101
Project Leader
Posts: 2697
Joined: Sat Jul 07, 2012 1:59 am

Re: @staticmethod question

Postby satoon101 » Thu Dec 14, 2017 10:30 pm

I would also like to amend my previous response to say that if it is a "classmethod", then this statement would be true (replacing static with class in both instances):

Syntax: Select all

# Since it's a static method, it should be called like this:
fifty = MyClass.my_static_method(10)
Image
User avatar
BackRaw
Senior Member
Posts: 537
Joined: Sun Jul 15, 2012 1:46 am
Location: Germany
Contact:

Re: @staticmethod question

Postby BackRaw » Wed Dec 20, 2017 10:40 pm

I like your way of approaching this, thanks.

Return to “Plugin Development Support”

Who is online

Users browsing this forum: No registered users and 23 guests