@classmethod while python programming..

Home Forums Python Programming @classmethod while python programming..

Viewing 1 post (of 1 total)
  • Author
    Posts
  • #1941 Reply
    Humble
    Keymaster

    As you know, its possible to define a method with decorator called “classmethod”..

    >>>> @classmethod
    ... def first():
    ...     print "I am first"
    ... 
    
    >>>
    
    
    
    How-ever what advantage it brings ?
    
    That said, A class method is a bound method except that the class of the instance is passed as an argument rather than the instance itself.
    
    
    >>> class Sports(object):
    ...     @classmethod
    ...     def fun(cls, x):
    ...             print ("%s %s") %(cls,x)
    ... 
    >>> foot = Sports()
    >>> foot
    <__main__.Sports object at 0x7fa5c9872a50>
    >>> foot.fun
    <bound method type.fun of <class '__main__.Sports'>>
    
    
    Look at above, its a bound method of "CLASS" ..
    
    
    
    >>> foot.fun("ball")
    First arg:<class '__main__.Sports'> => Second arg: ball
    
    
    
    Secondly, to call a method inside a class, the class has to be instantiated .., but with classmethod decorator its possible to invoke the class methods without its instance getting created as shown below
    
    
    
    >>> Sports.fun("cricket")
    First arg:<class '__main__.Sports'> => Second arg: cricket
    
    
    
    
    
    
    `
    >>> Classfs = type("Classfs",(object,),{"any":first})
    >>> Classfs.any()
    I am first
Viewing 1 post (of 1 total)
Reply To: @classmethod while python programming..
Your information: