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()
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to