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?

--

DaveA

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to