On Tuesday, January 7, 2020 at 7:58:41 AM UTC-5, Edward K. Ream wrote:
>
> While working on leoAst.py, I have come to understand more fully several 
> of Vitalije's suggested code patterns:
>
> *Prefer functions to classes/methods*
>
> Classes and methods are essential in python. They aren't going away. 
> However, in some cases functions are preferable to methods, for several 
> reasons:
>
> 1. Functions are available "everywhere".  In contrast, methods are 
> available only within their enclosing class.
>
> Methods can be used outside their class, say within another class, only be 
> instantiating a "helper" instance of the method's class.  That's a clumsy 
> pattern.
>
> This isn't quite  as true as you might think.  You can reuse them - in 
other classes - by direct assignment:

Class A:
    def func1(self, parms):
        # Do something here

Class B:
    func2(self, parms) = A.func1

# or

   def func2(self, parms):
      return A.func1(self, parms)

Where you can get into trouble is when class A's init code causes conflicts 
with class B.  So you have to be thoughtful about initialization.

Basically, there isn't a lot of difference between a function and a 
method.  It's the difference between

result = self.method1(parms)

and 

result = function1(instance, parms)

A class method is helpful when the function is closely tied to how the 
class works, or needs to use a lot of its state.  A function is more 
helpful when it isn't tied so closely to a particular class, or doesn't 
need to use much of its state.

We are fortunate with Python because we can have both, unlike say Java.

-- 
You received this message because you are subscribed to the Google Groups 
"leo-editor" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to leo-editor+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/leo-editor/bd1e5ff2-2a5c-490d-8498-17adf86dcc46%40googlegroups.com.

Reply via email to