python - Where is the best place to put support functions in a class? -


in python, have class i've built.

however, there 1 method apply rather specific type of substring-search procedure. procedure standalone function (it requires needle haystack string), feels odd have function outside class, because class depends on it.

what typical design paradigm this? typical have myclassname.py main class, support functions outside class itself, in same file? or better have support function embedded within class @ expense of modularity?

you can create staticmethod, so:

class yo:     @staticmethod     def say_hi():         print "hi there!" 

then, can this:

>>> yo.say_hi() hi there! >>> = yo() >>> a.say_hi() hi there! 

they can used non-statically, , statically (if makes sense).

about put functions...

if method required class, , appropriate method perform data specific class, make method. want:

class yo:     self.message = "hello there!"     def say_message(self):         print self.message 

my say_message relies on data particular instance of class.

if feel need have function, in addition class method, means go ahead. use whichever 1 more appropriate in script. there many examples of this, including in python built-ins. take generator objects example:

a = my_new_generator() a.next() 

can done as:

a = my_new_generator() next(a) 

use whichever more appropriate, , whichever 1 more readable. :)


Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -