ffejrekaburb
ffejrekaburb

Reputation: 731

Python class with class method

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

Answers (1)

Grismar
Grismar

Reputation: 31319

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.

Upvotes: 3

Related Questions