Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function in a python class that is not a method

Tags:

python-2.7

I have a class that needs auxiliary functions, e.g. one to calculate a checksum that just uses the passed in arguments and not any properties of the class. This function is only called by the class's methods. So I dont need to pass in the 'self' as the first formal of the function.

How should I implement these functions? Can I have non-method functions in a class? Should I define them outside the class (even though they are not used by anything else)? Or is it ok for them to be regular methods?

like image 684
spiderplant0 Avatar asked Sep 12 '13 00:09

spiderplant0


People also ask

Which is not class method in Python?

Explanation: The assignment of more than one function to a particular operator is called as operator overloading. 2. Which of the following is not a class method? Explanation: The three different class methods in Python are static, bounded and unbounded methods.

Is a Python function a method?

A method in python is somewhat similar to a function, except it is associated with object/classes. Methods in python are very similar to functions except for two major differences. The method is implicitly used for an object for which it is called. The method is accessible to data that is contained within the class.

IS function and method the same in Python?

Difference between Python Methods vs FunctionsMethods are associated with the objects of the class they belong to. Functions are not associated with any object. We can invoke a function just by its name. Functions operate on the data you pass to them as arguments.

Can I use a function I defined outside a class Python?

Yes you can definitely have functions outside of a class.


1 Answers

Just do a nested function:

class Foo(object):
    def bar(self, arg):
        def inner(arg):
            print 'Yo Adrian imma in inner with {}!'.format(arg)

        inner(arg)    

Foo().bar('argument')      

Or just ignore the self:

class Foo(object):

    def prive(_, arg):
        print 'In prive with {}!'.format(arg)


    def bar(self, arg):
        def inner(arg):
            print 'Yo Adrian imma in inner with {}!'.format(arg)

        inner(arg)   
        self.prive(arg)

    def foo(self,arg):
        self.prive(arg)     

Foo().bar('argument')
Foo().foo('another argument') 

Second example prints:

Yo Adrian imma in inner with argument!   
In prive with argument!
In prive with another argument!
like image 69
dawg Avatar answered Oct 06 '22 23:10

dawg