Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 14331

Specify default attribute value in Python class

$
0
0

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?


Viewing all articles
Browse latest Browse all 14331

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>