Methods

This is something that we have covered already. As mentioned earlier, methods are the functionalities of an object. The only difference with usual functions here is that, these functions are instantiated by the objects using a self variable.

Looking back at the last example:

You can use the white space on your Repl window and RUN the code at the end to see the result.

class starters:
    def newfunction(self):
        print('hello, there')

s = starters()
s.newfunction()

print(s)

This outputs:

hello, there
<__main__.starters instance at 0x04046EE0>

Here, newfunction() is the method that uses self to refer to the object/instance of the Class. We can observe that even though the method newfunction() doesn't input any parameters, we still use self for the reference.

The __init__ method

This is an important method associated with Classes and objects in Python. The method name consists of two underscores before and after init. This method runs at the time when an object of a class is instantiated. As the name goes, it's used to initiliaze the variables of an object. For example:

class Cars:

    def __init__(self,color):
        self.color = color

    def colorOfCar(self):
        print('The color of my car is ' + self.color)

c = Cars('Red')
c.colorOfCar()

This results in:

The color of my car is Red

This is an example to showcase the class Cars. It has an __init__ method that initializes the color of the car using the user's input, or we can also pass default values.

class Cars:

    def __init__(self):
        self.color = 'Red'

    def colorOfCar(self):
        print('The color of my car is ' + self.color)

c = Cars()
c.colorOfCar()

This has the same result:

The color of my car is Red

NOTE: The speciality of the __init__ method is that we don't call it explicitly. It is called by default in Python.

results matching ""

    No results matching ""