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

Python Object-Oriented Python (retired) Inheritance Inheritance Quiz

What 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
Vidhya Sagar
1,568 Points

You 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 .

In your example, you had to use the def keyword in order to create the add method.

Vidhya Sagar
Vidhya Sagar
1,568 Points

Yes.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.

I 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
Vidhya Sagar
1,568 Points

Sorry didnt notice that .But hope that Add example method served your purpose .