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 trialPeter Smith
1,550 PointsNot fully understanding @classmethod
I have rewatched the video and have tried looking to see if their was a question like this on treehouse but found their wasn't. Here is the code challenge: "Let's practice using @classmethod! Create a class method in Letter named from_string that takes a string like "dash-dot" and creates an instance with the correct pattern (['_', '.'])." I had some trouble understanding the point of classmethod and staticmethod and am getting frustrated with course.
class Letter:
def __init__(self, pattern=None):
self.pattern = pattern
def __iter__(self):
yield from self.pattern
def __str__(self):
output = []
for blip in self:
if blip == '.':
output.append('dot')
else:
output.append('dash')
return '-'.join(output)
@classmethod
def from_string(cls, dashdot):
for dash in dashdot:
print(dash)
for dot in dashdot:
print(dot)
class S(Letter):
def __init__(self):
pattern = ['.', '.', '.']
super().__init__(pattern)
2 Answers
Chris Freeman
Treehouse Moderator 68,454 PointsYou are on the right path. Here are the next steps:
-
dashdot
is a string with “dash”s and “dot”s separated by hyphens (“-“). you will need to use thesplit('-')
method to get each item that might be a dot or a dash. - with a single
for
loop, create a list of “.” and “_” - the
cls
parameter points to the current class. You can usecls(dot_dash_list)
to create a new instance ofLetter
using the list created in the previous step -
return
this new instance
Post back if you need more help. Good luck!!!
Kautilya Kondragunta
492 Pointsclass Letter:
def __init__(self, pattern=None):
self.pattern = pattern
def __iter__(self):
yield from self.pattern
def __str__(self):
output = []
for blip in self:
if blip == '.':
output.append('dot')
else:
output.append('dash')
return '-'.join(output)
@classmethod
def from_string(cls, str_pattern):
x = str_pattern.split('-')
for item in x:
if x[x.index(item)] == 'dash':
x[x.index(item)] = '_'
elif x[x.index(item)] == 'dot':
x[x.index(item)] = '.'
return cls(x)