Thursday 7 April 2011

Python Class Attributes. A Quiz!

So take a look at this code.

#! /usr/bin/env python
'''
A simple class demonstrating attributes
'''
ID_COUNTER = 0

class Person(object):
    genus = "homo sapien"

    def __init__(self, name, sex="M"):
        global ID_COUNTER
    
        assert sex in ("M", "F"), 'INVALID SEX "%s" must be "M" or "F"'% sex
        ID_COUNTER += 1
        self.id = ID_COUNTER
        self.name = name
        self._sex = sex
        self._profession = None

    @property
    def sex(self):
        return "Male" if self._sex=="M" else "Female"

    @property
    def profession(self):
        if self._profession is None:
           return "unknown"
        return self._profession

    def set_profession(self, profession):
        self._profession = profession

    def __repr__(self):
        return "Person %03d:\n\t%s\n\tGenus\t(%s)\n\t%s\n\t%s"% (
            self.id,
            self.name,
            self.genus,
            self.sex,
            self.profession)

if __name__ == "__main__":
    person1 = Person("Neil")
    person1.set_profession("dentist")

    person2 = Person("Joan", "F")
    person2.genus = "Neanderthal"

    person3 = Person("Timrit", "M")
    person3.set_profession("refrigeration")
    
    for object_ in (Person.genus, person1, person2, person3):
        print object_
        print

which gives the following output

homo sapien

Person 001:
 Neil
 Genus (homo sapien)
 Male
 dentist

Person 002:
 Joan
 Genus (Neanderthal)
 Female
 unknown

Person 003:
 Timrit
 Genus (homo sapien)
 Male
 refrigeration


And here are your questions.
1. Why is the Global statement used on line 11?
2. is there a better way of implementing a unique serial ID for these objects?
3. What would happen if I tried to create an instance with the following call?
person4 = Person("ArtV61", "unknown")
4. is genus a "class attribute" or an "instance attribute"?
5. what is the difference between a "class attribute" or an "instance attribute"?
6. is Person an old or new style class?
7. what would need to change in this code to make it run under python3?
8. what is the __repr__ function for, and what would be the output if it were deleted?
9. what namespace is the __name__ variable found in?
10. why is the trailing underscore used for object_ on the penultimate line of code?


Answers, as always to linc AT thelinuxlink.net, quoting "QUIZ" in the subject field.

No comments: