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 trialAshley Wong
1,454 PointsWhat keyword do you use to create a method on a class?
What keyword do you use to create a method on a class?
1 Answer
Vidhya Sagar
1,568 PointsYou do not need any special keyword for creating a method on a class ,but you'll have to pass an argument called self which refers to the object you are going to create with the class .Like this
class Add():
def add(self):
self.num1=5
self.num2=10
self.add=print(self.num1+self.num2)
Now in this every time you create an object the object will be refernced to self when the fuction is called . You needn't worry about this much ,just remember that everytime you define an method inside a class pass an argument called self .
Jason Anello
Courses Plus Student 94,610 PointsJason Anello
Courses Plus Student 94,610 PointsIn your example, you had to use the
def
keyword in order to create the add method.Vidhya Sagar
1,568 PointsVidhya Sagar
1,568 PointsYes.def is a keyword you have to use for creating any method, weather it's inside or outside a class .What I meant was you don't need any additional special keyword for creating a method on a class.
Jason Anello
Courses Plus Student 94,610 PointsJason Anello
Courses Plus Student 94,610 PointsI was only pointing it out because you omitted that from your answer and you talked about the
self
argument instead. The quiz question didn't have anything to do with that.Vidhya Sagar
1,568 PointsVidhya Sagar
1,568 PointsSorry didnt notice that .But hope that Add example method served your purpose .