Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Derek Derek
8,744 PointsPython: argument of a class in Think Bayes by Allen B. Downey
I am studying Bayes' Theorem with Think Bayes by Allen B. Downey. I am following his python scripts, and there is one line that I don't understand. Here's thinkbayes.py http://www.greenteapress.com/thinkbayes/thinkbayes.py and the line I don't understand is in dice.py http://www.greenteapress.com/thinkbayes/dice.py, specifically the first line of main(): suite = Dice([4, 6, 8, 12, 20]). Here, a list of [4, 6, 8, 12, 20] is passed into Dice class, a subclass that inherits Suite class in thinkbayes.py line 1060. Suite doesn't have an init method, and it inherits Pmf class in line 360, which in turn inherits _DictWrapper in line 105. Here's what I don't understand: what does ' suite = Dice([4, 6, 8, 12, 20]) ' exactly do and how? Thank you for your help in advance!
1 Answer
Jason Anello
Courses Plus Student 94,610 PointsHi Derek,
I don't know anything about Bayes' Theorem but I can try explaining how the code is being processed when you create a Dice object.
You were able to trace it up to the _DictWrapper class which does contain an __init__ method. This is the method that will be called when you initialize your Dice object. The list will be stored in the local parameter values
Here's the code that is doing something with the argument that is passed in to initialize it:
init_methods = [
self.InitPmf,
self.InitMapping,
self.InitSequence,
self.InitFailure,
]
for method in init_methods:
try:
method(values)
break
except AttributeError:
continue
A list of 4 methods in the _DictWrapper class are set up. These are then tried in turn with the for loop. If a method can't process the values passed in then a AttributeError will be raised and it will continue to the next method.
InitPmf will fail because it's expecting a Pmf object and a list was passed in. InitMapping will fail as well because it's expecting a mapping of values to probabilities.
InitSequence is the one that should work out since it's expecting a sequence and a list is a sequence.
InitFailure raises a ValueError if none of the first 3 methods work out.
Derek Derek
8,744 PointsDerek Derek
8,744 PointsThank you so much! It clarifies just what I need to know!