In this topic, we will look at class methods in detail.
So far, we've seen how to add attributes to an object. As we mentioned earlier, objects are also comprised of behaviors known as methods. Now we will take a look at how to add our own methods to classes.
We'll rewrite our original Person class to include a speak() method. The steps are as follows:
Create a speak() method in our Person class, as follows:
class Person: def __init__(self, name, age, height_in_cm): self.name = name self.age = age self.height_in_cm = height_in_cm def speak(self): print("Hello!")
The syntax for defining an instance method is familiar. We pass the argument self which, as in the __init__ method, refers to the current object at hand. Passing self will allow us to get or set the object's attributes inside our function. It is always the first argument of an instance method.
Instantiate...