[Tutor] static methods & class methods

Walter Prins wprins at gmail.com
Fri Apr 20 23:41:31 CEST 2012


Hi Surya

On 20 April 2012 17:32, Surya K <suryak at live.com> wrote:

> I mean, say I defined foo() , bar() methods in a class myClass. So, how
> can we i use foo() in bar(). I tried to use @staticmethod, @classmethod,
> but I am getting some errors..
>
> sometimes saying "unbound " and sometimes "given more than 1 parameters"
> .. can any one tell me how to do this...
>

Please, just copy *exactly* what you've done, and the exact error message.
The above implies you got the syntax slightly wrong but without code and
without the exact stack trace we must guess.

That said, my spidey sense tells me you want to declare a classmethod.  You
do it like this:

#define a class Foo and define a class method in it:
class Foo:
    @classmethod  #decorator to indicate this is a class method
    def class_method(self): #for class methods, self refers to class itself
        print "This is a classmethod called from class", self

#call the class method:
Foo.class_method()

Aside, @staticmethod is simpler, it is basically is a way to declare a pure
function (not bound to an object instance or a class as such, e.g. it
doesn't receive a "self" parameter) as part of a class.

Cheers,

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120420/84a1abf6/attachment-0001.html>


More information about the Tutor mailing list