[Tutor] Difference(s) betweenPython 3 static methods with and without @staticmethod?

Alan Gauld alan.gauld at yahoo.co.uk
Sun Aug 6 20:06:27 EDT 2017


On 07/08/17 00:35, boB Stepp wrote:

> =========================================================================================
> Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64
> bit (AMD64)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
> py3: class MyClass:
> ...     def my_method():
> ...             print('This is my_method in MyClass!')
> ...
> py3: class MyOtherClass:
> ...     @staticmethod
> ...     def my_other_method():
> ...             print('This is my_other_method in MyOtherClass!')
> ...
> py3: MyClass.my_method()
> This is my_method in MyClass!
> py3: MyOtherClass.my_other_method()
> This is my_other_method in MyOtherClass!

You should also try calling them from an instance of the class.
That should also illustrate a difference between classmethod and
staticmethod when you get round to that.

> the entry "staticmethod(function)" the author states, "... Use the
> @staticmethod functiion decorator in version 2.4 and later ... In
> Python 3.X only, this built-in is not required for simple functions in
> classes called only through class objects (and never through instance
> objects)."  

Notice the bit in parens...
It doesn't say you cannot call staticmethods from instances,
it says that you don;t need the decorator unless you are
doing that. Very different.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list