0

I have to create a function, printObjects(attribute, option), which must print the objects based on a certain attribute. The attribute can take ints or strings as input. The option attribute is optional. How do I implement this for my class?

Trim
  • 375
  • 1
  • 5
  • 14
  • 2
    "The option attribute is optional" what?!?! I hope this means that the 2nd parameter of printObjects, which is named 'option', is not mandatory. Otherwise i am very confused with the different uses of option/attribute. Assuming you meant what i hope, what is option for? and what does it default to? – jon_darkstar Nov 10 '10 at 17:31
  • *print* *the* *objects* *based* *on* *a* *certain* *attribute* what is this supposed to mean? :-| – fortran Nov 10 '10 at 17:41

1 Answers1

1

I assume you want something like this, or perhaps it will be helpful at least:

def printObject(obj, attributes=()):
  for a in attributes:
     print getattr(obj, a)
mkm
  • 1,545
  • 1
  • 14
  • 21
  • 7
    **Never use something mutable as default argument.** (Unless you actually know how it works and *want* this behaviour; also, it won' resul tin any bugs *in this example* but it's better to point this out anyway) See http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument –  Nov 10 '10 at 17:41
  • In this case it's fine, 'attributes' isn't written to. – dan_waterworth Nov 10 '10 at 20:05
  • 1
    This was the right way to do it. Thanks. Sorry about my ambiguity in the original question, but this guy got what I meant :) – Trim Nov 11 '10 at 03:24
  • @delnan, you are right that the the mutable argument is dangerous. It was to make the code easy to read, but I can use a tuple to achieve the same effect – mkm Nov 11 '10 at 09:18
  • @Trim: If this answer is correct for you, then accept it (use the tick to the left of the answer). – Björn Pollex Nov 11 '10 at 09:26