天天看点

终于学到PYTHON的类啦~~

#!/usr/bin/python

# filename:objvar.py

class robot:

    '''represents a robot,with a name.'''

    population = 0

    def __init__(self,name):

        '''iinitializes the data.'''

        self.name = name

        print('(initialize {0})'.format(self.name))

        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 master call me{0}.'.format(self.name))

    def howmany():

        '''print 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-3p0')

droid2.sayhi()

print('\nrobots can do some work here.\n')

print("robots have finished their work. so let's destroy them.")

del droid1

del droid2

终于学到PYTHON的类啦~~