crimes in Python

Martin von Loewis loewis at informatik.hu-berlin.de
Wed Mar 8 13:17:36 CET 2000


kragen at dnaco.net (Kragen Sitaker) writes:

> class Victim:
> 	def __init__(self, crime, type, crimeno, age, sex, race):
> 		self.crime = crime
> 		self.type = type
> 		self.crimeno = crimeno
> 		self.age = age
> 		self.sex = sex
> 		self.race = race
> 		self.suspects = []

If your typical way to process all those fields is a 6-tuple, then it
may be more convenient to store it as a 6-tuple, and allow by-name
access via methods:

class Victim:
    def __init__(self,fields);
        if len(fields)!=6: raise TypeError('fields come in sixpacks')
        self.fields = fields
        self.suspects = []
    def crime(self): return self.fields[0]
    ...


> 		victim = Victim(
> 			crime = fields[0], 
> 			type = fields[1], 
> 			age = fields[3],
> 			sex = fields[4],
> 			race = fields[5],
> 			crimeno = fields[6])

Then you'd just write

  victim = Victim(fields)

> 	sys.stdout.write(join (
> 		(victim.crimeno,
> 		victim.crime,
> 		victim.type,
> 		victim.age,
> 		victim.sex,
> 		victim.race),
> 		"\t"))

Here, it would be

  sys.stdout.write(join(victim.fields, '\t'))

I just noticed you have a different order here, so you'd probably use
the accessors here.

Regards,
Martin



More information about the Python-list mailing list