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
1 Answer 1
It really depends on the context. Your options:
- a global function
As in your example code. This would make the function visible to all who import your module, just as the class itself is.
def function1():
return=1+1
function1()
- a global, but 'hidden' function
Use a name that starts with an_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()
- a class method
This really only makes sense if the method need access to something on the class, which is why it is passed a reference to the class.
@classmethod
def function1(cls):
return=1+cls.some_class_attribute
self.function1()
- a static method
This may be what you're looking for, as it limits access to the function to whoever has access to the class (or an instance), but it does not allow access to the class or instances itself.
@staticmethod
def function1():
return=1+1
self.function1()
- and finally, you may want to hide the class or static method
For the same reason as before, perhaps you only want methods in the class itself to have access, not everyone who has a hold of the class or an instance.
@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.
3 Comments
import my_module, then yes, you'd call it with my_module.function1() (assuming you are talking about the global function). But if you import like from my_module import function1, you can just call it using function1().
function1actually lives, or provide a couple of examples if you're trying to cover multiple scenarios?function1actually does in relation toget_allobjects; there are many ways to approach this. Based on what you are showing though,function1should be just fine where you show it.get_allobjectsis a member of".