Accessing attributes?

Jeff Rollin jeffrey.rollin at gmail.com
Tue Jun 12 12:04:52 CEST 2007


Hi there.

I'm working with the Python Tutorial "Byte of Python" at swaroopch.info.

I have created the following file:

------------------------------------------------------------------------
#!/usr/bin/env python
# Filename: objvar.py

class Person:
    """Represents a person."""
    population = 0    # class variable

    def __init__(self,name):
        """Initializes the person's data."""
        self.name = name     # object variable
        print '(Initializing %s)' % self.name

        # When this person is created, he/she adds to the population
        Person.population += 1

        def __del__(self):
            """I am dying."""
            print '%s says bye.' % self.name

            Person.population -= 1

            if Person.population == 0:
                print 'I am the last one.'
            else:
                print 'There are still %d people left.' % Person.population

        def say_hi(self):
            """Greeting by the person.

            Really, that's all it does."""
            print 'Hi, my name is %s.' % self.name

        def how_many(cls):
            """Prints the current population."""
            if Person.population == 0:
                print 'Nobody is alive as of now.'
            elif Person.population == 1:
                print 'There is just one person here.'
            else:
                print 'We have %d persons here.' % Person.population
        how_many = classmethod(how_many)

#jeff = Person('Jeff')

#jeff.say_hi()

cj = Person('Calamity Jane')
#cj.say_hi()
Person.how_many()

#jeff.say_hi()
Person.how_many()
---------------------------------------------------------------------------------

 but when I execute:

% objvar.py

I get the error message:

(Initializing Calamity Jane)
Traceback (most recent call last):
  File "/home/jef/bin/objvar.py", line 49, in <module>
    Person.how_many()
AttributeError: class Person has no attribute 'how_many'

Where am I going wrong?

Many TIA for any help.



More information about the Python-list mailing list