Objects can call methods, which are defined methods are defined in classes. Methods can modify all variables of an object.
Inside the class you have to use the self keyword, which refers to the instance created from the class.
Because methods can be called from an object (instance), they are sometimes called instance methods.
Related course: Python Programming Courses & Exercises
python class methods
If you have a class Phone, you can create one or more new phone objects (instances). If you say define the class Phone you can create the object Nexus. In code that would look like this:
class Phone: |
In this example the class has a method addContact()
. We call this method on the object, by typing object.method()
. In this case, object.addContact()
.
The function will add a new contact to the list, but it doesn’t matter which function you define or what it does.
In the example above, we create an object Nexus. On this object we can call the methods call() and addContact(). Those methods are defined in the class, but change the objects variables.
The core idea is that an object can have one or more methods. If you call the method, it can change the objects properties.
nexus = Phone() |
Create class method
To make this method call work, the method called on the object addContact()
needs to exist within the class Phone
.
While we’re at it, also add a contact list to the class (all objects variables are defined inside the class).
class Phone: |
Do you see the self keyword in the code above, this refers to the current objects variables.
The class itself has the methods and variables:class Phone:
contacts = []
def call(self):
print('Calling')
def addContact(self, name):
self.contacts.append(name)
Every object you create has unique variables. If you create 3 objects, all of them have their own unique variables.
Related course: Python Programming Courses & Exercises
In the next article we’ll discuss the self keyword.