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 trialPabba Anu Bharath
2,049 PointsNot able to get the task 2 from the last challenge in Regular Expression Course:
Question: Wow! OK, now, create a class named Player that has those same three attributes, last_name, first_name, and score. I should be able to set them through init.
I am new to python. Can you please explain me how to solve this question.
import re
string = '''Love, Kenneth: 20
Chalkley, Andrew: 25
McFarland, Dave: 10
Kesten, Joy: 22
Stewart Pinchback, Pinckney Benton: 18'''
regex = re.compile(r'^(?P<last_name>[a-zA-Z\s]+),\s(?P<first_name>[a-zA-Z\s]+):\s(?P<score>[0-9]+)$', re.MULTILINE)
players = re.search(regex, string)
class Player:
last_name = ""
first_name = ""
score = 0
Pabba Anu Bharath
2,049 PointsHi Chris, Thanks for reaching to help. Sorry I've updated the code now.
2 Answers
Chris Freeman
Treehouse Moderator 68,441 PointsThe next step is to add an __init__
method. It should take self
and keyword arguments last_name
, first_name
, and score
. Use these kwargs to set the local attributes.
Post back if you need more help. Good luck!!
Pabba Anu Bharath
2,049 PointsI get an error : Wasn't able to create correct instances. Got {}.
import re
string = '''Love, Kenneth: 20
Chalkley, Andrew: 25
McFarland, Dave: 10
Kesten, Joy: 22
Stewart Pinchback, Pinckney Benton: 18'''
regex = re.compile(r'^(?P<last_name>[a-zA-Z\s]+),\s(?P<first_name>[a-zA-Z\s]+):\s(?P<score>[0-9]+)$', re.MULTILINE)
players = re.search(regex, string)
class Player:
last_name = ""
first_name = ""
score = 0
def __init__(self,**kwargs):
last_name,first_name,score =kwargs
Chris Freeman
Treehouse Moderator 68,441 PointsIt's better, in this case, to explicitly list each keyword argument in the __init__
. Also the assignments need to be to attributes in the form self.last_name = last_name
Pabba Anu Bharath
2,049 PointsThanks a lot Chris!
Chris Freeman
Treehouse Moderator 68,441 PointsChris Freeman
Treehouse Moderator 68,441 PointsWhat have you tried?