In [1]:
class MyFirstClass:
    def __init__(self, name):
        self.name = name

    def greet(self):
        print('Hello {}!'.format(self.name))
In [2]:
my_instance = MyFirstClass('John Doe')
print('my_intance: {}'.format(my_instance))
print('type: {}'.format(type(my_instance)))
print('my_instance.name: {}'.format(my_instance.name))
my_intance: <__main__.MyFirstClass object at 0x1050163c8>
type: <class '__main__.MyFirstClass'>
my_instance.name: John Doe

Methods

The functions inside classes are called methods. They are used similarly as functions.

In [3]:
alice = MyFirstClass(name='Alice')
alice.greet()
Hello Alice!

__init__()

__init__() is a special method that is used for initialising instances of the class. It's called when you create an instance of the class.

In [4]:
class Example:
    def __init__(self):
        print('Now we are inside __init__')
        
print('creating instance of Example')
example = Example()
print('instance created')
creating instance of Example
Now we are inside __init__
instance created

__init__() is typically used for initialising instance variables of your class. These can be listed as arguments after self. To be able to access these instance variables later during your instance's lifetime, you have to save them into self. self is the first argument of the methods of your class and it's your access to the instance variables and other methods.

In [5]:
class Example:
    def __init__(self, var1, var2):
        self.first_var = var1
        self.second_var = var2
        
    def print_variables(self):
        print('{} {}'.format(self.first_var, self.second_var))
        
e = Example('abc', 123)
e.print_variables()
    
abc 123

Class variables vs instance variables

Class variables are shared between all the instances of that class whereas instance variables can hold different values between different instances of that class.

In [6]:
class Example:
    # These are class variables
    name = 'Example class'
    description = 'Just an example of a simple class'

    def __init__(self, var1):
        # This is an instance variable
        self.instance_variable = var1

    def show_info(self):
        info = 'instance_variable: {}, name: {}, description: {}'.format(
            self.instance_variable, Example.name, Example.description)
        print(info)


inst1 = Example('foo')
inst2 = Example('bar')

# name and description have identical values between instances
assert inst1.name == inst2.name == Example.name
assert inst1.description == inst2.description == Example.description

# If you change the value of a class variable, it's changed across all instances
Example.name = 'Modified name'
inst1.show_info()
inst2.show_info()
instance_variable: foo, name: Modified name, description: Just an example of a simple class
instance_variable: bar, name: Modified name, description: Just an example of a simple class