[Tutor] Staticmethod & Classmethod Question

Chris Kavanagh ckava3 at gmail.com
Sun Feb 26 02:02:38 CET 2012



On 2/25/2012 4:34 AM, Dave Angel wrote:
> On 02/25/2012 03:31 AM, Chris Kavanagh wrote:
>> Hey Everyone,
>>
>> I came across this code in 'A Byte Of Python' & realized there was a
>> line I didn't understand. The line is "howMany =
>> staticmethod(howMany)" (Complete code pasted below.)
>>
>> I don't think, in my very short Python career, I've heard of a
>> staticmethod or classmethod. There's very little explanation of them
>> in the book. I've googled them, but am still confused on exactly what
>> they are & why they should be used. The only sense I can make of them
>> is, a staticmethod can be called WITHOUT actually creating an object
>> first.
>>
>> Anyways, if someone could give me a simple explanation with a very
>> simple example, I will be elated! As always, thank you in advance for
>> any help!! Code Below:
>>
>> PS: Please keep in mind, Python is my 1st language, & I'm very new to
>> it (4 to 5 months).
>>
>>
>>
>> class Robot:
>> '''Represents a robot, with a name.'''
>>
>> # A class variable, counting the number of robots
>> population = 0
>>
>> def __init__(self, name):
>> '''Initializes the data.'''
>> self.name = name
>> print('(Initializing {0})'.format(self.name))
>>
>> # When this person is created, the robot
>> # adds to the population
>> Robot.population += 1
>>
>> def __del__(self):
>> '''I am dying.'''
>> print('{0} is being destroyed!'.format(self.name))
>>
>> Robot.population -= 1
>>
>> if Robot.population == 0:
>> print('{0} was the last one.'.format(self.name))
>> else:
>> print('There are still {0:d} robots working.'.format(Robot.population))
>>
>> def sayHi(self):
>> '''Greeting by the robot.
>>
>> Yeah, they can do that.'''
>> print('Greetings, my masters call me {0}.'.format(self.name))
>>
>> def howMany():
>> '''Prints the current population.'''
>> print('We have {0:d} robots.'.format(Robot.population))
>> howMany = staticmethod(howMany)
>>
>> droid1 = Robot('R2-D2')
>> droid1.sayHi()
>> Robot.howMany()
>>
>> droid2 = Robot('C-3PO')
>> droid2.sayHi()
>> Robot.howMany()
>>
>> print("\nRobots can do some work here.\n")
>>
>> print("Robots have finished their work. So let's destroy them.")
>> del droid1
>> del droid2
>>
>> Robot.howMany()
>
> Defining a function inside a class makes it a method. Two distinctions
> exist between an ordinary function and a method. One is which namespace
> the name is known in, and the other is this mysterious thing called self.
>
> The namespace thing means that "sayHi" for example is not an attribute
> of the module, but of the instance of the class. So other classes might
> have a method of the same name without conflict.
>
> The self thing means that when you say droid2.sayHi(), there is an extra
> parameter added to the list (only one in this case), the 'self' parameter.
>
> What staticmethod() does is to strip out the second feature. For methods
> that don't need a 'self' parameter, (ie. that don't care which instance
> they're called on, and are willing to hardcode any refs to other class
> things) this works out great.
>
> classmethod() converts the method so it supplies the class of the object
> as its first parameter (cls). This can be useful if you have more than
> one class derived from each other, and the method still needs to know
> which class it actually was called on.
>
> Does this help some?
>
Yes & No, lol. BTW, thanks for the reply Dave, it's much appreciated.

Maybe if I tell you what I know, it will make it easier for you to 
understand what I don't know. Such as, I know a method is just a 
function inside a class. . .

Ok, 1st, I learned Classes & Objects using Python 'Old Style' Classes & 
Objects. I hadn't thought (until now) there was much difference other 
than terminology, ie. using class(object): in the parent class. Instead 
of class(self): ect.

2nd, I understood 'self' is just a place holder for the object that will 
be created.

I get that a staticmethod does not need the 'self', but why would this 
be necessary?? You said,

  "For methods
 > that don't need a 'self' parameter, (ie. that don't care which instance
 > they're called on, and are willing to hardcode any refs to other class
 > things)"

I know this will sound stupid, but why would the method care which 
instance it's called on?? I think this is where my confusion is coming 
in. . .I hope I've made sense here. . .


More information about the Tutor mailing list