[Tutor] method, type?

Alex Kleider akleider at sonic.net
Thu Jan 7 14:42:18 EST 2016


Thank you to all who contributed to this thread.
It has helped me immensely and I enjoyed some of the spirited 
discussion.

Some of my notes follow (in case corrections are in order:-)

     my_notes = """

     @staticmethod
     def s_method(param_but_no_self_or_cls):
         # An ordinary function that resides in the class to associate
         # its functionality with the class.
         pass

Instance methods expect 'self'.    | arranged implicitly when called
Class methods expect 'cls'.        | via instance or class.

"factory" methods (typically called '.from_*') can be:
     1. a normal function outside the class, or
     2. a class method (would allow subclassing.)
     "alternative constructor" (what Petter Otten and Steven DAprano
     call it,) would be best placed immediately after __init__.
     Alan Gauld indicates that as initially written (without
     '@staticmethod') "it is not" ?a method/function?
     but a 'named constructor' which is not supported by Python, so
     it could be a 'class method.'  He recommends making it a factory
     function (defined at the module level, outside the class.)
     Steven DAprano calls it a Python3 regular function/ a Python2
     broken method and mentions the Descriptor protocol and how
     'methods' are initially simply functions that are then converted
     to methods (bound) as required. In my case it would be an
     'unbound' method which works in 3 but not in Python2.

Cameron Simpson indicated that putting @staticmethod above my 'method'
would be OK (although not preferred.)  Present or absent, my method
still functions the same way.
The table provided by Peter Otten (very helpful:)
-----------------------------------------------------------------
invoked with | @staticmethod  | @classmethod    | no decorator
------------------------------------------------------------------
class        | args unchanged | class as 1st arg | args unchanged
instance     | args unchanged | class as 1st arg | inst as 1st arg
-------------------------------------------------------------------
It suggests that use of the @staticmethod serves to protect one should
the 'method' be called via an instance rather than the class.  Has it
any other effect?

"""



More information about the Tutor mailing list