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
Aaron Banerjee
6,876 Pointsdoes @class method and __init__ correlate/work together if written in the same class
from dice import D20
class Hand(list):
def __init__(self, size=0, die_class=D20, *args, **kwargs):
super().__init__()
for _ in range(size):
self.append(die_class())
# self.sort()
@classmethod
def roll(cls, size):
return cls(size)
@property
def total(self):
return sum(self)
in this case here, if i use the roll class method to get the classes size, does the init use the classes size in order to to create a list for the class. This is for the rpg roller code challenge by the way thanks for any help
1 Answer
Eray Ates
14,292 PointsI'm not sure you ask for this but clean our heads
...
@classmethod #use this one return an instance of class or change general attribute of class
def roll(cls, size):
return cls(size) # now cls turn to Hand like that Hand(size) and eval Hand(size) and this goes to __init__ method
oneInstance = Hand.roll(5)
secondInstance = Hand(5)
So same mean try this to get length:
#without classmethod
def roll(self):
return len(self)