I would like to construct a class where an initial attribute depends on the result of an external function and gives a default value otherwise. E.g., Puzzle
has a default score of the length of the string used to initialize it, but if no string is provided, its score is -1.
class Puzzle: def __init__(self, string): self.score = len(string) || -1
This obviously doesn't work as no such syntax is allowed.
One way to do this is with try-except
:
class Puzzle: def __init__(self, string): self.score = -1 # probably redundant try: self.score = len(string) except: self.score = -1 # could this be pass instead?
Is there a more concise way to do it?