Reputation: 731
I have a python class such as the following
def function1():
return=1+1
class Collection()
...
@classmethod
def get_allobjects(cls):
..logic here..
retval = function1()
function1 is encapsulated from the outerlying class but needs to be available for get_allobjects. What would be the best way to define this function? Should it be defined as a class method or can it be left as a stand alone function inside of the same python file (defined before the class?)? Any advice or pointers on style would be appreciated.
Thanks, Jeff
Upvotes: 0
Views: 93
Reputation: 31319
It really depends on the context. Your options:
def function1():
return=1+1
function1()
_
to indicate that it's not supposed to be used externally. People still can, but it would generate warnings.def _function1():
return=1+1
_function1()
@classmethod
def function1(cls):
return=1+cls.some_class_attribute
self.function1()
@staticmethod
def function1():
return=1+1
self.function1()
@staticmethod
def _function1():
return=1+1
self._function1()
It all depends on how visible you want the function to be and whether or not the logic of the function is really independent of the class, or whether it only makes sense in context of the class.
There's more options still, for example defining the function as a sub-function of the method itself, but that's only really sensible if the construction of the function itself somehow depends on the state of the class/object when it is constructed.
Upvotes: 3